How to create <input type = "text" / "> dynamically
I want to create input type text in my web form dynamically. More specifically, I have a text field in which the user enters the number of desired text fields; I want the text fields to be generated dynamically in the same form.
How to do it?
With JavaScript:
var input = document.createElement("input"); input.type = "text"; input.className = "css-class-name"; // set the CSS class container.appendChild(input); // put it into the DOM Using Javascript, all you need is document.createElement and setAttribute .
var input = document.createElement("input"); input.setAttribute('type', 'text'); Then you can use appendChild to add the created element to the desired parent element.
var parent = document.getElementById("parentDiv"); parent.appendChild(input); Perhaps the document.createElement(); method document.createElement(); - this is what you are looking for.
You can do something similar in a loop based on the number of input text fields.
$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform'); But for better performance, I would first create all of the html and inject it into the DOM only once.
var count = 20; var html = []; while(count--) { html.push("<input type='text' name='name", count, "'>"); } $('#myform').append(html.join('')); This example uses jQuery to add html, but you can easily change it and use innerHTML.
You can use the createElement() method to create this text field.
I think the following link will help you. If you want to generate fields dynamically and also want to delete them at the same time, you can get help from here. I had the same question, so I got the answer
$(function() { var scntDiv = $('#p_scents'); var i = $('#p_scents p').size() + 1; $('#addScnt').live('click', function() { $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv); i++; return false; }); $('#remScnt').live('click', function() { if( i > 2 ) { $(this).parents('p').remove(); i--; } return false; }); }); See this answer for a solution without jQuery. Just helped me!
Adding dynamic input elements to a form
Here is my solution
function fun() { /*getting the number of text field*/ var no = document.getElementById("idname").value; /*text fields to be generated dynamically in the same form*/ for(var i=0;i<no;i++) { var textfield = document.createElement("input"); textfield.type = "text"; textfield.id = "idname4textfeild"; textfield.setAttribute("value",""); document.getElementById('form').appendChild(textfield); } } <form id="form"> <input type="type" id="idname" oninput="fun()" value=""> </form>