Reputation: 7577
I read so many questions about this problem, but whatever I do, it doesn't work.
I have several checkboxes with dynamic IDs, like those:
More:
<input type="checkbox" name="more" id="checkbox-more-285">
<br> Extra:
<input type="checkbox" name="extra" id="checkbox-extra-285">
<button class="add_to_cart">
Add to cart
</button>
The number 285 can be anything, that I use elsewhere.
Then I have this jQuery:
jQuery('.add_to_cart').click(function(e) {
e.preventDefault();
if (jQuery("[id^='checkbox-more-']:checked")) {
console.log('1');
}
if (jQuery("[id^='checkbox-extra-']:checked")) {
console.log('2');
}
return false;
});
As you can see on the jsFiddle here https://jsfiddle.net/, whenever I click on add to cart button, both logs are on console.
Upvotes: 0
Views: 927
Reputation: 1761
you can use either
jQuery("[id^='checkbox-more-']").is(":checked")
{
console.log('1');
}
or
if($("[id^='checkbox-more-']").prop('checked') == true){
console.log('1');
}
Upvotes: 0
Reputation: 350137
It is not enough to test for the jQuery collection, which will always be truthy. Add the .length
property to the test, like this:
if (jQuery("[id^='checkbox-more-']:checked").length) { // etc...
Upvotes: 3