Ok so I need to be able to click any element inside .modal-interest
, and it for it to check the child-element checkbox when they are clicked.
Currently, it seems to work for the first click - but for every subsequent click, even though the code is supposed to be checking the checkbox, it does nothing.
$('.modal-interest strong').click(function (e) {
input = $(this).closest('.modal-interest').find('input');
if (input.prop('checked')) {
input.attr('checked', false).change();
} else {
input.attr('checked', true).change();
}
});
An accurate representation of my problem can be seen on the following fiddle:
Stuck with this and would appreciate any help!
You should use .prop()
instead:
$('.modal-interest strong').click(function (e) {
input = $(this).closest('.modal-interest').find('input');
if (input.prop('checked')) {
input.prop('checked', false).change();
$('h1').html('untick it');
} else {
input.prop('checked', true).change();
$('h1').html('tick it');
}
});
Now indeed, your code should look like this instead:
$('.modal-interest strong').click(function (e) {
var input = $(this).closest('.modal-interest').find('input')[0];
input.checked = !input.checked;
$(input).change();
});
$('.modal-interest input[type=checkbox]').on('change', function () {
$('h1').html(this.checked ? 'tick it' : 'untick it');
});
应该使用prop方法。
input.prop('checked', false).change();
Try this code:
$('.modal-interest').click(function () {
var input = $(this).find('input');
if (input.prop('checked')) {
input.prop('checked', false).change();
$('h1').html('untick it');
} else {
input.prop('checked', true).change();
$('h1').html('tick it');
}
});
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.