Loek Loek - 1 year ago 64
HTML Question

How to add and remove HTML elements depending on number in input field

I have a number input field in which a user can enter a number. Depending on this number, some new input fields are generated.

Currently I have no problems adding fields, as long as the new number put in by the user is higher than the previous. I can't remove the generated fields if the user puts in a lower number though.

So i.e. a user types in '5', which generates 5 new fields. If the user adjusts this number to '3', there are still 5 generated fields.

Input HTML

<input type="number" class="form-control" name="amount_of_vote_groups" id="amount_of_vote_groups">

Javascript (jQuery)

var i = 1;
$('#amount_of_vote_groups').change(function () {
while (i <= this.value) {
'<div class="form-group" id="generated-field-'+i+'">' +
// Some other stuff here
if (this.value > i) {
$('#right-column').remove('#generated-field-' + i);

I know I'm doing something stupid with the
statement, but I just can't it get figured out. I'm a real sucker at javascript ;)

Answer Source

I'd do it like this:

$('#amount_of_vote_groups').change(function() {
  $('#right-column div.form-group').remove();
  for (var i = 1; i <= this.value; i++) {
      '<div class="form-group" id="generated-field-' + i + '">div</div>'

jsFiddle example

Whenever you change the number input, clear out any divs that may exist, then spin through a loop to add the new ones.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download