I have a page with multiple forms (all the forms have the same classes, just unique IDs). The form has a functionality where people can enter their starting and ending work date. There is also a checkbox for "I currently work here", and if that is checked, the ending work date input field will be replaced with the word "present" instead.
Clicking/toggling the checkbox works just fine for each separate form. The issue is that when the checkbox in one form is pre-checked, all the other forms have the word 'present' even if the checkboxes in the respective forms are not checked.
Here's my jQuery code:
$(document).ready(function () {
if ($('.checkbox-present').length) {
var presentCheckBox = $('.checkbox-present');
var endYear = $(presentCheckBox).parents('.checkbox-parent').find('.position-end');
if ($(presentCheckBox, endYear).is(':checked')) {
$('.form-group', endYear).hide();
$(endYear).append('<p class="position-present">Present</p>');
}
} else {
$('.position-present', endYear).remove();
$('.form-group', endYear).show();
}
});
$('.checkbox-present').change(function () {
var endYear = $(this).parents('.checkbox-parent').find('.position-end');
if ($(this).is(':checked')) {
$('.form-group', endYear).hide();
$(endYear).append('<p class="position-present">Present</p>')
} else {
$('.position-present', endYear).remove();
$('.form-group', endYear).show();
}
});
Fiddle here to properly see the effect.
As you can see from the fiddle, Form 2 has the word "present" even if its checkbox is unchecked. I'm certain it's because of the checkbox in Form 1.
How do I fix this? I'm still finding my way around jQuery so I'm not sure how to solve this, but I think it has something to do with binding?
Aucun commentaire:
Enregistrer un commentaire