Zagorodniy Olexiy
Zagorodniy Olexiy

Reputation: 2212

How to add or delete fields depending on value of another field

I have form:

<div class="fieldWrapper">
<label for="id_rooms">Rooms:</label>
<input id="id_rooms" type="number" name="rooms" min="1">
</div>

<div class="extrafieldWrapper">    
</div>

Depending on number of rooms i want to add or delete new fields "adult" and "children". For example: if value of field "room" will be 2, it should generate two couples another fields for each room 'adult' and 'children', but if change value from 2 on 1, it should delete one couple of fields. And when change the value of 'room' field from 2 to 3, it should add one couple of fields. I saw many examples how to do this on java-script, so i try to write the script by my self, but it doesn't work correctly. Depending on value of field 'room' it only add new couple of fields.

$(function() {

var newFields = $('');
$('#id_rooms').bind('blur keyup change', function() {
    var n = this.value || 0;
    if (n + 1) {
        if (n > newFields.length) {
            addFields(n);
        } else {
            removeFields(n);
        }
    }
});

function addFields(n) {
    for (form_num = newFields.length; form_num < n; form_num++) { 
        $("input[id='id_form-TOTAL_FORMS']").attr('value', form_num + 1);
        $(".extrafieldWrapper").append("<br/><label for='id_form-" + form_num + "-adult'>Adult:</label> <input id='id_form-" + form_num + "-adult' type='number' name='form-" + form_num + "-adult'/> <label for='id_form-" + form_num + "-children'>Children:</label> <input id='id_form-" + form_num + "-children' type='number'  name='form-" + form_num + "-children'/> ");
    }
}

function removeFields(n) {
    $('.extrafieldWrapper').html('');
}

});

I am newbie in java-script, can you tell me what i'm doing wrong. Thanks a lot.

Upvotes: 1

Views: 94

Answers (1)

onerror
onerror

Reputation: 616

It's a bit unclear what behavior exactly you wanted. Here I tried to represent it with code:

$(function () {
  $('#id_rooms').bind('blur keyup change', function () {
    var n = $('#id_rooms').val() || 0;
    $("input#id_form-TOTAL_FORMS]").attr('value', n);
    $(".extrafieldWrapper").empty();
    for (var i = 0; i < n; i++) {
      $(".extrafieldWrapper").append("<br/><label for='id_form-" + i + "-adult'>Adult:</label> <input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/> <label for='id_form-" + i + "-children'>Children:</label> <input id='id_form-" + i + "-children' type='number'  name='form-" + i + "-children'/>");
    }
  });
});

Anyway, you don't need two functions for adding and removing fields. You only need to rewrite the whole content of your div in one cycle. Or, if you prefer two functions approach, then you need to gather all the tags describing one pair of fields you add/remove under one div or span and give each of such groups an unique id by which you would address it.

Upvotes: 1

Related Questions