I want to create an input type text in my web form dynamically. More specifically, I have a textfield where the user enters the number of desired text fields; I want the text fields to be generated dynamically in the same form.
How do I do that?
I want to create an input type text in my web form dynamically. More specifically, I have a textfield where the user enters the number of desired text fields; I want the text fields to be generated dynamically in the same form.
How do I do that?
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 append the created element to the desired parent element.
var parent = document.getElementById("parentDiv");
parent.appendChild(input);
Maybe the method document.createElement();
is what you're looking for.
You could do something like this in a loop based on the number of text fields they enter.
$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');
But for better performance I'd create all the html first 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(''));
Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.
You could use createElement()
method for creating that textbox
I think the following link will help you. If you want to generate fields dynamically and also want to remove them on the same time you can get the 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;
});
});
http://jsfiddle.net/jaredwilli/tZPg4/4/
See this answer for a non JQuery solution. Just helped me out!
Adding input elements dynamically to form