vendredi 20 février 2015

Checkbox added dynamically using jquery doesn't accept correct values when submitted

I am using a django-formset having a textbox and a checkbox, and dynamically updating the number of forms on the page using jQuery. The dynamically updated text inputs do send the correct values when submitted, while the checkboxes always send false. This is the code snippet I am using to update the form elements:



function updateElementIndex(el, prefix, ndx) {

var id_regex = new RegExp('(' + prefix + '-\\d+-)');
var replacement = prefix + '-' + ndx + '-';
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex,
replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}

function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (formCount > 2) {

$(btn).parents('.item').remove();

var forms = $('.item'); // Get all the forms
// Update the total number of forms (1 less than before)
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
var i = 0;
// Go through the forms and set their indices, names and IDs
for (formCount = forms.length; i < formCount; i++) {
$(forms.get(i)).children().children().children().children().each(function () {
if ($(this).attr('type') == 'text') updateElementIndex(this, prefix, i);
});
}
} // End if
else {
alert("You have to enter at least two elements!");
}
return false;
}

function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());

// You can only submit a maximum of 10 todo items
if (formCount < 5) {
// Clone a form (without event handlers) from the first form
var row = $(".item:first").clone(false).get(0);
// Insert it after the last form
$(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300);

// Remove the bits we don't want in the new row/form
// e.g. error messages
$(".errorlist", row).remove();
$(row).children().removeClass("error");

// Relabel or rename all the relevant bits
$(row).children().children().children().children().each(function () {
updateElementIndex(this, prefix, formCount);
$(this).val("");
if ($(this).is('input[type="checkbox"]')) {
$(this).removeAttr('checked');

}
});

// Add an event handler for the delete item/form link
$(row).find(".delete").click(function () {
return deleteForm(this, prefix);
});
// Update the total form count
$("#id_" + prefix + "-TOTAL_FORMS").val(formCount + 1);
} // End if
else {
alert("Sorry, you can only enter a maximum of 5 elements.");
}
return false;
}
// Register the click event handlers
$("#add").click(function () {
return addForm(this, "form");
});

$(".delete").click(function () {
return deleteForm(this, "form");
});


How do I make the form accept the correct values for checkboxes?





Aucun commentaire:

Enregistrer un commentaire