Reputation: 10483
I am using jQuery 1.4.3
I have several input that look like this:
<input type='checkbox' id='1' class='Product' comp='1'>
<input type='checkbox' id='2' class='Product' comp='1'>
<input type='checkbox' id='3' class='Product' comp='1'>
<input type='checkbox' id='4' class='Product' comp='2'>
<input type='checkbox' id='5' class='Product' comp='2'>
<input type='checkbox' id='6' class='Product' comp='2'>
If a box with the Product class is clicked I want to get its comp value and uncheck the other boxes that have a different comp value.
Normally, I would loop through and check each comp value and then uncheck where necessary, like this pseudo code:
ThisComp == 1 // comp value of checkbox that was just clicked
$(".Product").each(function() {
var Comp $(this).attr("comp");
if (ThisComp != Comp) {
// $(this).attr("checked", false);
}
});
I am wondering if there is a way to filter using the comp value in the selector, such as this pseudo code:
$(".Product comp=2").attr("checked", false);
The goal here is to uncheck any box that has a different comp value than the one clicked in an efficient way.
Upvotes: 1
Views: 251
Reputation: 95027
This should work:
$('.Product[comp="2"]').removeAttr("checked");
UPDATE
var comp = $(this).attr("comp");
$('.Product[comp="' + comp + '"]').removeAttr("checked");
Upvotes: 1
Reputation: 185893
How about this:
$( '#boxes' ).delegate('input:checkbox', 'click', function () {
var comp = +$( this ).attr( 'comp' );
$( this ).siblings().not( '[comp="' + comp + '"]' ).prop( 'checked', false );
});
Live demo: http://jsfiddle.net/BMtTy/
Or with data-attributes:
$( '#boxes' ).delegate('input:checkbox', 'click', function () {
var comp = +$( this ).data( 'comp' );
$( this ).siblings().not( '[data-comp="' + comp + '"]' ).prop( 'checked', false );
});
Live demo: http://jsfiddle.net/BMtTy/1/
Upvotes: 2
Reputation: 300
It's actually quite easy. However, it is invalid to create custom attributes without using data-*. Use data-comp
instead. Another small note, cache your selection and filter it for added performance. I recommend something like this:
var $productChecks = $('.Product');
$productChecks.click(function() {
var compValue = $(this).attr('data-comp');
$productChecks
// Uncheck boxes that don't have the same comp value
// Since checked is a boolean attribute, use prop to set
// Quote attribute value in selectors
.filter('[data-comp!="' + compValue + '"]').prop('checked', false).end()
// If desired, make sure the ones that have the same value are checked
.not(this).filter('[data-comp="' + compValue + '"]').prop('checked', true);
});
Upvotes: 1
Reputation: 78630
http://api.jquery.com/category/selectors/
$(".Product[comp!='2']").attr("checked", false);
Upvotes: 1