Dynamically add textbox using jquery
from the link above i want something like that, but i want to use dropdown menu.
here is my code
http://jsfiddle.net/boyee007/VyG6F/
the textbox will be added depends on the value.
if you select 3 will only show 3 textboxes, and if 2 will only show 2 textboxes and so on
Add a comment
|
2 Answers
Try something like this:
$("#ppl").change(function(){
// The easiest way is of course to delete all textboxes before adding new ones
//$("#holder").html("");
var count = $("#holder input").length;
var requested = parseInt($("#ppl").val(),10);
if (requested > count) {
for(i=count; i<requested; i++) {
var $ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'});
$("#holder").append($ctrl);
}
}
else if (requested < count) {
var x = requested - 1;
$("#holder input:gt(" + x + ")").remove();
}
});
See it running here.
2 Comments
tonoslfx
thanks :). works great. but i dont want it continuesly add the textbox when i select another value. if you
select 5 will it only shows 5 textboxes, then if you select 3 (it only show 3 textboxes), NOT add another 3 textboxes. i hope that make sense :)kgiannakakis
See my edited answer. Although it will be easier to delete everything and start from scratch, the user will lose any text she had already entered. For this reason on update I add/remove required elements to reach the correct count.