Dan W Dan W - 5 months ago 23
jQuery Question

jQuery - Compare data-attr to search term

I am trying to compare a data-attribute to a search term like so:

var searchArea = $('#indexContainer');
var searchVal = $('#search').val();
var items = $('.processLink');

var links;

$('#search').keyup(function() {
// on search input key up

//for each .processLink
$.each(items, function(index, value) {
//get the selector
var selected = $(value);

//get the keywords
var keywords = selected.data('keywords');

//console.log(selected.attr('id'));

$("#" + selected.attr('id') + ":contains('" + searchVal + "')").css("text-decoration", "underline");
});

});


so if I have a few divs like these

<div id="div1" class="processLink" data-keywords="div one cat dog"></div>
<div id="div2" class="processLink" data-keywords="div blade cow horse"></div>
<div id="div3" class="processLink" data-keywords="div camera bag"></div>
<div id="div4" class="processLink" data-keywords="div"></div>


Then I just want to check on the key up whether the search term entered in to
search input matches any of the terms in data-keyword attribute and if they do then only show the .processLink divs which have the related words and hide the rest. I know I currently have it trying to underline, that was just a test

Hopefully that makes some kind of sense

Answer

There are many issues with the above code.

  1. Value of the input should be fetched inside keyup

  2. You don't need each in case you have a jQuery collection $('.processLink'); already defined.

  3. :contains( checks for content inside the div and not its attributes. You would need attribute contains selector - [attribute *=..] for this.

Fiddle


$(function(){
    var $divs = $('.processLink');
    $('#search').keyup(function() {
        var searchVal = this.value;
        $divs.css("text-decoration", "none");
        $divs.filter('[data-keywords*="'+searchVal+'"]').css("text-decoration", "underline");
    });
});
Comments