How can I click the add button to show the information in the input field and display it in a <p> tag that is created using JavaScript? (without using inline JavaScript)

Is there a way to dynamically add user input to the page without using inline JavaScript and with minimal HTML? I want to create a new paragraph element through JavaScript when the user clicks a button, instead of relying on static elements in the HTML.

<body>
<div class="input">
    <form>
        <input id="input" type="text" placeholder="Enter task to do..." />
        <button id="add_btn">Add</button>
    </form>
</div>
<div class="task_list">
    <ul id="todo">
        <li></li>
    </ul>

</div>


<script>
   //take user input and add it to the page as a task to do
   let div = document.querySelector('.task_list');
   let input = document.querySelector('#input')
   let pElement = document.createElement('p');
   let add = document.getElementById('add_btn');

   div.appendChild(pElement);

    add.addEventListener(onclick, function (){
        input.value;
        pElement.innerHTML = input;
        console.log(add);
    });

 </script>

Answer №1

Your code has a few issues to address:

  1. Make sure to use 'click' instead of onclick when binding the event listener.
  2. Define the type attribute as type="button" for the button element to prevent page refreshing on click.
  3. Ensure to create a new p element in the event listener and set its content using input.value.

The provided snippet should help resolve these issues, steering you in the right direction for your end goal.

// Take user input and add it to the page as a task to do
let div = document.querySelector('.task_list');
let input = document.querySelector('#input')
let add = document.getElementById('add_btn');

add.addEventListener('click', function() {
  let pElement = document.createElement('p');
  pElement.textContent = input.value;
  div.appendChild(pElement);
});
<div class="input">
  <form>
    <input id="input" type="text" placeholder="Enter task to do...">
    <button type="button" id="add_btn">Add</button>
  </form>
</div>
<div class="task_list">
  <ul id="todo">
    <li></li>
  </ul>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular fails to function properly post rendering the body using ajax

I recently created a HTML page using AJAX, and here is the code snippet: <div class="contents" id="subContents" ng-app=""> @RenderBody() @RenderSection("scripts", required: false) </div> <script src="http://ajax.googleapis.com/ajax/ ...

Attempt the axios request again if the response is null or missing

await axios .post( executeBatch, { headers: { "Content-Type": "application/json", "x-access-token": localStorage.getItem("token"), }, } ) .then( ...

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...

I have encountered an issue where after declaring a JavaScript variable on a specific page, including the JavaScript file does not grant access to it

<script type="text/javascript"> $(document).ready(function () { var SOME_ID= 234; }); </script> <script type="text/javascript" src="<%= HtmlExtension.ScriptFile("~/somefile.js") %>"></script> ...

Find the item that has a specific value in its sub-property

Information Models: public class Header{ public int Identifier; public int value; public bool anotherValue; public List<Trailer> trailers; } public class Trailer{ public int ID; public Language MyLanguage; public string ...

Steps to installing npm on Ubuntu without root access:1. First, download

I have successfully installed node in a custom directory within my home folder called "local" following the instructions provided here: https://gist.github.com/isaacs/579814 Here is the output: Creating ./icu_config.gypi * Utilizing ICU in deps/icu-sma ...

How to extract data from Google Sheets using NODEJS?

When utilizing the REST API to extract data from a cell range in Google Sheets, the response returned is as follows: { "range": "RECORD!A2:J2", "majorDimension": "ROWS", "values": [ [ "07/11/2016", "21:20:10", "3", "MAIN" ...

Launching a new window and displaying content across 2 separate tabs

Currently, I am incorporating both angular js and javascript within my application. An issue that has arisen is that when I click on the <a> tag, it triggers a method in an angular controller which contains $window.open();. The problem lies in the fa ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...

ajax call triggering knockout foreach update

Within my ViewModel, I have defined a variable called self = this; Another foreach binding is working in my code, but it is not within an ajax request. The initial UI load is functioning correctly. I have confirmed that self.wikiData is being updated by ...

Concealing and Revealing a Div Element in HTML

Every time the page is refreshed, I am encountering a strange issue where I need to double click a button in order to hide a block. Below is the code snippet for reference: <!DOCTYPE html> <html> <head> <meta name="viewport&quo ...

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

eliminate the script and HTML comment from a designated division

Here is the default code that I need to modify using JavaScript to remove scripts, comments, and some text specifically from this div: I came across this script that removes all scripts, but I only want to remove specific ones from this div: $('scri ...

Issue with AngularJS ngGrid rendering incorrect page size and malfunctioning pagination

I'm currently working on implementing ngGrid data pagination for some data retrieved from a service. The table displays correctly and the search filter is functional. However, despite setting the pageSize in my pagingOptions to 25, the table shows all ...

Encountered a issue during the installation of an NPM module

I am a beginner in the world of web development. I attempted to set up an npm module using the command npm install grunt-contrib-watch --save-dev, however, I encountered the following error: npm WARN npm npm does not support Node.js v0.10.37 npm WARN npm ...

Display the div element only when the mouse is hovering over the button

I need a hidden text inside a div that will only appear when the mouse pointer is hovering over a specific button. Here is my current code: // Show help-text on hover $("#help-container") .mouseover(function(e) { $(this).find("#help-t ...

Error found when combining a stopwatch with the react useState hook and setInterval, causing an additional interval to start when the stopwatch

I have implemented a stopwatch feature that includes start and pause buttons. The start button triggers setInterval while the pause button calls clearInterval. Initially, pressing start and then pause works correctly. However, if you press start again afte ...

The request is not functioning as expected for some reason

My current challenge involves retrieving photos from Instagram using a GET request. I attempted to use jQuery.get(), which has been successful for other types of GET requests but not for Instagram. Despite trying to switch to jQuery.getJSON(), the issue pe ...

Querying Techniques: Adding an Element After Another

CSS <div id="x"> <div id="y"></div> <div> <p>Insert me after #y</p> The task at hand is to place the p tag after '#y', and whenever this insertion occurs again, simply update the existing p tag instead of ...