Answer the question
In order to leave comments, you need to log in
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>
$(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);
}
} );
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question