javascript - no of input fields according to user input -


i have form ask number of input fields user, , append inputs form. have developed function using javascript.

the problem first time work fine. if again select number select tag, append number of input fields previous inputs.

example:

  • if first select 4 input fields show 4 input fields.
  • if again select 2 select tag add 2 input fields.

so altogether 6 input fields. don't want that. if select 4 should 4. if again select 2 should 2, not 6. here code:

function obj(){      var a=document.getelementbyid('no_of_obj').value; //select tag value(1 6)     var b=document.getelementbyid('objblock') //this container     var i=0;      while(i<a){         var txt=document.createelement('input');         txt.type="text";         txt.id="obj"+i;         txt.style.height="30px";          b.appendchild(txt);         i++;     }  } 

try this

function obj(){      var a=document.getelementbyid('no_of_obj').value;//select tag value(1 6)     var b=document.getelementbyid('objblock')//this container     var i=0;      while(b.children.length < a){         var ct = document.createelement('div');         var txt=document.createelement('input');         txt.type="text";         txt.id="obj"+i;         txt.style.height="30px";         ct.appendchild(txt);         b.appendchild(ct)     }      while(b.children.length > a){         b.removechild(b.children[b.children.length - 1]);     } } 

demo: fiddle

using jquery

$(function(){     var $ct = $('#objblock');     $('#no_of_obj').change(function(){         var count = $(this).val(), counter = count - $ct.children().length;          while(counter-- > 0){             $('<div><input class="input-xlarge"/></div>').appendto($ct);         }          $ct.children(':gt(' + (count - 1) + ')').remove();     }); }) 

demo: fiddle


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -