(I've already read some other questions about this but none used this method)
I have some hidden fields that their respective checkboxes shows when checked and I'd also like to make these fields required when I check the checkbox and the opposite when unchecking.
When checking:
When unchecking:
This is what I'm trying but it's not working (the required part):
$(':checkbox').change(function(event) {
$(this).parent('.item').find('.input').toggleClass('hide', (!$(this).is(':checked')));
$(this).parent('.item').find('.input :checkbox').prop('checked', false, (!$(this).is(':checked')));
$(this).parent('.item').find('.input input').not(':checkbox, .opt').prop('required', true, ($(this).is(':checked')));
$(this).parent('.item').find('.input input').not(':checkbox').val('').not('.opt').prop('required', false, (!$(this).is(':checked')));
if (this.id == 'price2') {
$('.sub-rent .input').toggleClass('hide');
$('.rent :checkbox').prop('checked', false, (!$(this).is(':checked')));
$('.rent').toggleClass('hide', (!$(this).is(':checked')));
}
});
The html structure divides in three groups:
I'm also looking for the oportunity to know how could I optimze the code as much as possible.
As @PaulAbbott said, prop()
doesn't take three parameters, so:
$(':checkbox').change(function(event) {
$(this).parent('.item').find('.input').toggleClass('hide', (!$(this).is(':checked')));
$(this).parent('.item').find('.input :checkbox').prop('checked', false);
$(this).parent('.item').find('.input input').not(':checkbox').val('').not(':checkbox, .opt').prop('required', ($(this).is(':checked')));
if (this.id == 'price2') {
$('.sub-rent .input').toggleClass('hide');
$('.rent').toggleClass('hide', (!$(this).is(':checked')));
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.