1

Search elements based on data attributes. I have the following code and would like to know, how can this be achieved if the data attribute value with space

<div class="data" data-value="auto"> abcd </div>
<div class="data" data-value="simple tab,block"> acd </div>
<div class="data" data-value="auto"> abd </div>
<div class="data" data-value="block"> abcde </div>
<div class="null-data"> type the correct value </div>

<input class="search-text" name="keyword" type="text" id="search-keyword" placeholder="search">

On typing input value event I basically want to find out all the items that belong to a specific data-value?

$('#search-keyword').on( "keyup", function() {
$('.null-data').hide();
    if($(this).val()) {
        var input = $(this).val().toLowerCase();
        $(".data").hide();
        $(".data[data-value*="+ input +"]").show();
        if(!$('.data:visible').get(0)){
            $('.null-data').show();
        }
    }else{
        $('.null-data').show();     
    }
});

I'm getting the html elements based on data attribute values but if the data attribute value has space, the html elements are not showing up.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Raju28
  • 275
  • 1
  • 3
  • 10
  • 1
    Attributes values must not include spaces, you can use underscore instead – kapantzak Jan 08 '15 at 07:19
  • If feels a very common question. Please search before ask: http://stackoverflow.com/questions/4146502/jquery-selectors-on-custom-data-attributes-on-html5 – fjuan Jan 08 '15 at 07:46
  • @JohnKapantzakis: What? Sure they can. Attribute values can be any string. Attribute *names*, of course, are another story. – Nathan Tuggy Jan 08 '15 at 07:47

2 Answers2

4

while building the selector, you need to wrap the input value in quote as in contents meta character in it :

$(".data[data-value*='"+ input +"']").show();
//-------------------^-----------^
    if(!$('.data:visible').get(0)){
        $('.null-data').show();
    }

Workin Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You are using incorrect syntax.

Replace your code to this

$('#search-keyword').on( "keyup", function() {
$('.null-data').hide();
    if($(this).val()) {
        var input = $(this).val().toLowerCase();
        $(".data").hide();
        $(".data[data-value*="+ input +"]").show();
        if(!$('.data:visible').get(0)){
            $('.null-data').show();
        }
    }else{
        $('.null-data').show();     
    }
});
Manoj
  • 4,951
  • 2
  • 30
  • 56