A
A
Alexey2015-12-03 20:50:44
JavaScript
Alexey, 2015-12-03 20:50:44

How to create a form in which a certain number of fields would be added depending on the value of another field?

Hello, I have a form with a numeric field "rooms". Depending on the value of this field, I want the same number of new fields "Number of adults" and "Number of children" to be added. I'm writing a form application in Django. The HTML code for the form looks like this:

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

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

After searching the Internet for similar tasks, I wrote something of my own:
$(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++) { // lenght->length
        $("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) {
    var removeField = newFields.slice(n).remove();
    newFields = newFields.not(removeField);
}
} );

But this something does not work correctly: if I initially set the value to 2, then I get correctly - 2 new pairs of fields, but if I change the value from 2 to 3, then I will add not plus one pair of fields, but plus 3, or if I change the value from 2 to 1, then one pair of fields will not be deleted from me, but one will be added. Please help me as I am not very good with jquery. Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2015-12-04
@zago

I solved it!

$(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'/>");
    }
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question