0

I'm facing an issue in jquery. So, i just registered here. I need your help guys.

I'm using keyup function for matching ul li string. As per i type, the listitems scroll down/up to the specific text located li. But the issue is that when li has double text like

  1. Air balloon
  2. Balloon

then contains function stops on the Air balloon. Whereas i want the result which is having only Balloon text.

Basically i want that the search should perform from the very first letter.

Here is my code :

<ul>
    <li data-id="a">Air balloons</li>
    <li data-id="b">Balloons</li>
    <li data-id="l">List Items</li>
    <li data-id="i">Items</li>
</ul>

$(function(){
    $('input#search').keyup(function (e) {
        var searchValue = $(this).val();
        jQuery.expr[':'].contains = function (a, i, m) {
            return jQuery(a).text().toUpperCase()
                    .indexOf(m[3].toUpperCase()) >= 0;
        };
        var containText = $('li:contains(' + searchValue + ')');
        var id = containText.attr('data-id');
        alert(id);
    });
});

updating with jsfiddle

JSFIDDLE DEMO

Himesh Aadeshara
  • 2,114
  • 16
  • 26
Vik Verma
  • 15
  • 6
  • possible duplicate of [Jquery something like :contains(), but to match exactly phrase](http://stackoverflow.com/questions/7571117/jquery-something-like-contains-but-to-match-exactly-phrase) – ArBro Aug 24 '15 at 08:35
  • @VikVerma what you looking for case sensitive or insensitive or explain if else – Himesh Aadeshara Aug 24 '15 at 09:35

1 Answers1

0

You can use something like this, if you want exact text search:

$(function() {
  $('input#search').keyup(function(e) {
    var searchValue = $(this).val();
    if (searchValue.length == 0) {
      $('li').css('background-color', 'white');
    }
    $('li').each(function() {
      if ($(this).text().toLowerCase() == searchValue.toLowerCase()) {

        $(this).css('background-color', 'red');
        $(this).siblings().css('background-color', 'white');
        console.log($(this).attr('data-id'));

      }
    });
  });
});

Redundant lines here (coloring/remove color) are here just for demo purposes. Demo: http://jsfiddle.net/8xwchLg3/1/

So, basically - you want to check text() property of list items, iterate through li's with each(), if text of li equals your search value -> do what you want.

sinisake
  • 11,240
  • 2
  • 19
  • 27