Reputation: 19702
If it possible to search the DOM for labels based on part of their text?
For instance, if I have the following markup:
<input type="checkbox" id="1">
<label for="1">Check Box One</label>
<br />
<input type="checkbox" id="2">
<label for="1">Check Box Two</label>
<br />
<input type="checkbox" id="3">
<label for="1">Check Box Three</label>
<br />
I'd like to be able to search for "Box T" and get the last two labels. Or do I simply have to search for all labels, run an each query and then manually inspect the text values?
Upvotes: 1
Views: 684
Reputation: 105029
I think that the best and the most reusable solution would be to create a jQuery selector filter:
$.extend($.expr[":"], {
hastext: function(el, index, match) {
return $(el).text().indexOf(match[3]) >= 0;
}
});
That can then be used like this:
$("label:hastext('Box T')");
$("label:hastext(Box T)"); // would do the trick just as well
Hell it can be used on any selector afterwards
$("div.main table:first td:hastext(Get it?)")
This code is not tested and may not work as expected but you get the idea. It should at least check for having a value in match[3]
...
Upvotes: 1
Reputation: 6916
Maybe you put div around your label and input. Then you could hide and show that div according to your filters. I would put your text search as an attribute to separate visual stuff and logic (later you might localize your application and keep search keyword same, but user would see for example spanish text).
<label filterText="Check Box One" for="1">Check Box One</label>
Then using Attribute Contains selector you could look for your label and hide or show input + label using container div
$('label[filterText *= "your_keyword_here"]').each(function () {
// finds closest div and hides it
$(this).closest('div').hide();
});
I hope that this helps!
Upvotes: 0
Reputation: 66388
Looping will be the most simple way IMO:
var arrMatchingLabels = [];
$("label").each(function(index) {
if ($(this).html().indexOf("Box T") >= 0)
arrMatchingLabels.push($(this));
});
var s = "Found " + arrMatchingLabels.length + " matching labels: \n";
for (var i = 0; i < arrMatchingLabels.length; i++)
s += arrMatchingLabels[i].html() + "\n";
alert(s);
Upvotes: 0
Reputation: 1
why not searching for a checked input? set the ids of the checkboxes with relevant names. Add them a class and $('.searched_class:checked').val() will give you all the checked checkboxes values
Upvotes: 0