jQuery select by boolean data attribute
-
12-12-2019 - |
Question
I've got this line of code:
$(selector).find(":input[data-val=true]")
This will correctly select elements like this
<input type='number' data-val='true' />
But this will NOT select elements with alternate casing, like so: (note the capital T)
<input type='number' data-val='True' />
Besides putting in multiple selectors for different casing, what is a good way to make sure the selector returns the elements with the correct boolean value in it (even though it's a string"
FYI, the casing variance occurs due to my MVC application when I set the vlaue to an actual boolean, it will capialize this when it gets converted to a string :(
@Html.TextBox("quoteNumber", "", new { type = "number", data_val = true, data_val_required = "You must enter a quote number!" })
Solution
Use the .filter
method with a regexp:
$(selector).find(":input").filter(function(){
return /true/i.test($(this).attr("data-val"));
});
OTHER TIPS
in this case if you want to have a single jquery selector, you should use a REGEX for the boolean value :) it looks a bit hackish but it can solve your problem.