<div class="selectedColumns" > <a href="#" attributeid="19" >Driver License State</a> <a href="#" attributeid="21" >Email</a> <a href="#" attributeid="23" >Experience Level</a> <a href="#" attributeid="26" >First Name</a> <a href="#" attributeid="71" >Is Account Enabled</a> <a href="#" attributeid="39" >Last Contacted Date</a> <a href="#" attributeid="40" >Last Name</a> <a href="#" attributeid="41" >Middle Name</a> <a href="#" attributeid="6">Carrier</a> </div>
I have a collection of links. Each link has an attributeid property. I would like to filter by attribute value. So in the links above if I have a value of 41 it would return the Middle Name link.
var link = $('.selectedColumns a:[attributeid==' + $(this).val() + ']');
This did not work?
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.
The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us").
The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.
Not claiming this is any more elegant, but using filter() on a collection allows much more flexibility on what you can match on, and is a little less error prone than string concatenation.
var matching = $('.selectedColumns a').filter(function(){ return $(this).attr('attributeid') == 41 }); matching.prop('selected', true);
use a single = instead of 2. Also, the : shoudn't be there afaik
var link = $('.selectedColumns a[attributeid=' + $(this).val() + ']');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With