Reputation: 6607
I was thinking if there is a way to find if element's attribute contains a specified value. The attribute is unknown. If I have this HTML:
<input class="first" type="checkbox" data="THE-VALUE" />
<input class="second" type="checkbox" />
<input class="third" type="checkbox" name="THE-VALUE" />
I want to find all the inputs that has attribute with value THE-VALUE (in this case .first
and .third
). I don't need solution for this case where inputs are 3, but if I have 50 inputs and the attributes containing THE-VALUE are all different. I have tried things like .attr(':contains("THE-VALUE")')
and $('input[="THE-VALUE"]')
, but by obvious reasons it doesn't work.
So my question is .. is there any way to find that ?
Upvotes: 1
Views: 256
Reputation: 145378
$("input").filter(function() {
return $.grep(this.attributes, function(arg) {
return arg.nodeValue === "THE-VALUE";
}).length > 0;
}).prop("checked", true);
DEMO: http://jsfiddle.net/7tsZN/
Or as a selector extension:
$.expr[':'].hasattrval = function(e, i, p) {
return $.grep(e.attributes, function(arg) {
return arg.nodeValue === p[3];
}).length;
};
$("input:hasattrval('THE-VALUE')").prop("checked", true);
DEMO: http://jsfiddle.net/7tsZN/1/
Upvotes: 6