Javascript create input element

How to add, remove, input fields with javascript

Hello everyone, in this tutorial we are going to add, and remove, dynamically input form elements using javascript. We are going to see how to create elements with the createElement() method, and how to set attributes with the setAttribute() method.

I also have prepared a live demo which yo can try out.

Live example

Try out the example below.
Write some text in the input field and press the plus (+) sign.
You will see that a new input field is created and in the previous one the plus (+) sign is changed to a minus () sign. Create more than one input field and press the Display Notes button.

Please try out the example, it will give you a better understanding on what we are going to do.
Also if you scroll to the bottom of the page you can download the free source code.

Now that you have tried out the live demo, let’s see how we code this.

Project’s folder

Let’s see the files we need.

  • We need an index.html file, in which we are going to write the html form.
  • We need a script.js file, to write the javascript code.
  • And a styles.css file, to apply the basic style that we see in the example. I am not going to go through the css code, i will only explain the css properties that matters to the application. If you download the source code you will get the whole css code.
Читайте также:  Java does path exist

Now that we have setup the files, let’s go to the index.html file and write the html code.

The index file

In the index.html file we have a basic html structure, nothing fancy is going on here. The important things here are the link to the stylesheet in line 6, and the script tag that loads the javascript file in line 12.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Adding dynamically input fields</title> </head> <body> <script src="https://digitalfox-tutorials.com/script.js"></script> </body> </html> 

Inside the body tags we are going to write the html code that we need for our application to work.

<body> <div > <!-- the content will be created with javascript --> </div> 

The first element inside the body tags is a div element with a class of «notes». This element will be populated with javascript and will hold the text-notes, when we press the «Display Notes» button.

Next we have a form element.
Inside the form element we have a div element with a class of «field». And a submit button.

 <form action="" method="post"> <div > <input type="text" name="notes[]"> <span onclick="addField(this)">+</span> <span onclick="removeField(this)">-</span> </div> <button type="submit">Display Notes</button> </form> 
  • Inside the div with the class of «field» element and in line 16 we have the input field.
<input type="text" name="notes[]">
<span onclick="addField(this)">+</span> <span onclick="removeField(this)">-</span> 
<button type="submit">Display Notes</button>

And we are done with the index file, now let’s go to the script.js javascript file and write the functions to make the application to work.

The javascript file

Before we start writing our functions in the script.js file, let’s see them first.

  • We are going to have an addField() function, which function will create the new input field.
  • We are going to have a function named removeField(), which will remove the created input field.
  • We are going to have a function named fetchTextNotes(), which will display the values of the created input fields in the screen when we press the submit button.
  • And last we are going to have a function named markAsDone() which will add a checkmark in the text-note when we click on it.

Now we are ready to start writing our functions, and we are going to begin with the addField() function.

Adding new fields

Let’s start our javascript code with the addField() function. Remember that this function will run every time we click on the plus (+) sign.

function addField(plusElement) < let displayButton = document.querySelector("form button"); // Stopping the function if the input field has no value. if(plusElement.previousElementSibling.value.trim() === "")< return false; >// creating the div container. let div = document.createElement("div"); div.setAttribute("class", "field"); // Creating the input element. let field = document.createElement("input"); field.setAttribute("type", "text"); field.setAttribute("name", "notes[]"); // Creating the plus span element. let plus = document.createElement("span"); plus.setAttribute("onclick", "addField(this)"); let plusText = document.createTextNode("+"); plus.appendChild(plusText); // Creating the minus span element. let minus = document.createElement("span"); minus.setAttribute("onclick", "removeField(this)"); let minusText = document.createTextNode("-"); minus.appendChild(minusText); // Adding the elements to the DOM. form.insertBefore(div, displayButton); div.appendChild(field); div.appendChild(plus); div.appendChild(minus); // Un hiding the minus sign. plusElement.nextElementSibling.style.display = "block"; // the minus sign // Hiding the plus sign. plusElement.style.display = "none"; // the plus sign > 

Code breakdown

Let’s break the addField() function down.

    The function takes as an argument the plus span element.

function addField(plusElement)
 let displayButton = document.querySelector("form button"); 
 if(plusElement.previousElementSibling.value.trim() === "")
 let div = document.createElement("div"); div.setAttribute("class", "field"); 
  • In line 8 we creating the div element,
  • and in line 9 we set the class attribute to "field".
 let field = document.createElement("input"); field.setAttribute("type", "text"); field.setAttribute("name", "notes[]"); 
  • In line 11 we are creating the input element.
  • In line 12 we set the type attribute to "text",
  • and in line 13 we set the name attribute to the "notes[]" array, as we did in the html form.
 let plus = document.createElement("span"); plus.setAttribute("onclick", "addField(this)"); let plusText = document.createTextNode("+"); plus.appendChild(plusText); 
  • In line 16 we set the "onclick" event-listener as an attribute, and as its value we set the addField() function. So when we click on the new created plus sign we will create another new element. It's like a circle, a loop. Hope it makes sense.
  • In line 17 we create a textNode which is the plus + character inside the span element.
  • And in line 18 we append the textNode to the span element.
 let minus = document.createElement("span"); minus.setAttribute("onclick", "removeField(this)"); let minusText = document.createTextNode("-"); minus.appendChild(minusText); 
 form.insertBefore(div, displayButton); div.appendChild(field); div.appendChild(plus); div.appendChild(minus); 
  • In line 25 we are inserting the div container before the submit button. This way the new created element will always appear as the last element.
  • In line 26 we insert the input field in the div container.
  • In line 27 we inserting the plus span element in the div container.
  • And in line 28 we inserting the minus span element in the div container. With this last line of code we added in the div container all the new created elements.
 plusElement.nextElementSibling.style.display = "block"; plusElement.style.display = "none"; > // end of addField function. 

And we are done with the addField() function now let's write the removeField() function.

Removing a field

The removeField function runs every time we click on the minus span element.

function removeField(minusElement)

The function takes as an argument the minus span element. So we use the minus element and we target it's parent which is the div "field" container and remove the whole element. And that's it, that is all the code we need to remove an input field.

Displaying the textNotes

Next in our javascript file we are going to catch the text-notes and we are going to display them in the "notes" element that we have above our form in the html file.

let form = document.forms[0]; form.addEventListener("submit", fetchTextNotes); 
  • In line 38 we are targeting the html form element, and store it in the form variable.
  • And in line 39 we add an event-listener to the form element. The addEventListener method takes two arguments, the first argument is the event that we want to capture, in our case its the submit event, and as a second argument we pass in the name of the function that will run when we press the submit button. In our case this is the fetchTextNotes function.

Now let's write the fetchTextNotes function.

function fetchTextNotes(event) < event.preventDefault(); let data = new FormData(form); let notes = []; data.forEach( function(value)< if(value !== "")< notes.push(value); >>); let out = ""; for(let note of notes)< out += `&ltp>$ <span onclick="markAsDone(this)">Mark as done</span></p>`; > document.querySelector(".notes").innerHTML = out; let inputFields = document.querySelectorAll(".field"); inputFields.forEach(function(element, index)< if(index == inputFields.length - 1)< element.children[0].value = ""; >else < element.remove(); >>); > 

Code breakdown

Let's break the fetchTextNotes() function down.

    We are gonna pass in the function the event object as an argument. We do this because i need access to the preventDefault() method, so i can stop the form submit the data to the server.

function fetchTextNotes(event)< event.preventDefault(); 
 let data = new FormData(form); let notes = []; data.forEach( function(value) < if(value !== "")< notes.push(value); >>); 
  • In line 44 we use the formData object, and we pass in the form element. We are storing the returned data in the data variable.
  • Next in line 45 we create an empty array called notes.
  • In line 46 we loop through the data array using the forEach method.
  • In line 47 we check every value, and if it is NOT empty we store them in the notes array.
 let out = ""; for(let note of notes)< out += `&ltp>$ <span onclick="markAsDone(this)">Mark as done</span></p>`; > document.querySelector(".notes").innerHTML = out; 
  • In line 52 we creating a variable named out, and set the value to an empty string.
  • Next in line 53 we use a for of function to loop through the notes array.
  • In line 54 we adding in the out variable a paragraph element which holds the text-note and a span tag. In the span tag we display the text "Mark as done", and also we assign an onclick event-listener which fires the markAsDone() function.
    The markAsDone() function will replace the text inside the clicked span element with a checkmark. You saw this in the live demo.
  • And in line 56 we target the "notes" element in the index file and we use the innerHTML property to display the created text-notes.
 let inputFields = document.querySelectorAll(".field"); inputFields.forEach(function(element, index)< if(index == inputFields.length - 1)< element.children[0].value = ""; >else < element.remove(); >>); > // end of function 
  • In line 60 we use the querySelectoAll method to target all elements with a class of "field". The method returns a node-list, which we can handle as an array, and store it in the inputFields variable.
  • In line 61 we loop through all the "field" elements using a forEach function.
  • In line 62 we are checking if the current "field" element is the last inside the array. If the condition returns true we are setting the value to an empty string, else we remove the element.
    This way we end up with only one empty input field.

And we are done with the fetchTextNotes() function, now let's write our last function which is the markAsDone() function.

Mark as done function

The markAsDone() function takes as an argument the clicked span element, and replaces the text with the checkmark.

function markAsDone(element)
  • In line 71 we add the "mark"css class to the span element, this changes the color, the font-size, and tweaks the position.

And that's it we completed the application and the tutorial. Hope you like it.

Source code

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any errors, so i can update the page with the correct code.

You can download the source code and use it in any way you like. Get source code

View on Youtube

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Источник

как сделать input в js

Для создания input с помощью JavaScript можно использовать метод createElement для создания элемента input , а затем добавить его в DOM.

Пример создания input с типом "text":

const input = document.createElement('input'); input.type = 'text'; document.body.append(input); 

В этом примере мы создали элемент input , задали ему тип "text" и добавили его на страницу с помощью метода append .

Можем задавать и другие атрибуты для элемента input , такие как name , value , placeholder и т.д. Например, чтобы добавить атрибут name :

const input = document.createElement('input'); input.type = 'text'; input.name = 'myInput'; document.body.append(input); 

Как и для других элементов DOM-дерева, для данного input мы можем добавить обработчик события:

const input = document.createElement('input'); input.type = 'text'; input.addEventListener('input', (event) =>  console.log(event.target.value); >); document.body.append(input); 

Источник

Оцените статью