Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery filter by an attribute value

Tags:

<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?

like image 628
Mark Avatar asked Dec 28 '10 16:12

Mark


People also ask

How get data attribute value in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

What jQuery syntax selects HTML elements by a specific attribute and its value?

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").

How do we filter out elements using jQuery?

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.


2 Answers

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); 
like image 199
Jeff Lowery Avatar answered Sep 19 '22 15:09

Jeff Lowery


use a single = instead of 2. Also, the : shoudn't be there afaik

var link = $('.selectedColumns a[attributeid=' + $(this).val() + ']'); 
like image 23
Tjirp Avatar answered Sep 19 '22 15:09

Tjirp