0

I want to create a JQuery statement: when I input a value in the input field, the JQuery statement can select a list of items according to the content of tag.

For example, if I input "F" in the input field, list with id "2" and "3" can be selected.

Here is the HTML code:

<input id="test" type="text">
<ul id="myul" class="myul">
    <li id="1" class="a">
        <span>
            <b>Money</b>
            <i>Fish Money Food a</i>
        </span>
    </li>
    <li id="2" class="a">
        <span>
            <b>Food</b>
            <i>Fish Money Food b</i>
        </span>
    </li>
    <li id="3" class="a">
        <span>
            <b>Fish</b>
            <i>Fish Money Food c</i>
        </span>
    </li>
</ul>

However, I want a general solution, this general solution can also work for other HTML code in similar structure, for example:

<ul id="myul" class="myul">
    <li id="1" class="a">
        <a>Money</a>
        <i>Fish Money Food a</i>
    </li>
    <li id="2" class="a">
        <a>Food</a>
        <i>Fish Money Food b</i>
    </li>
    <li id="3" class="a">
        <a>Fish</a>
        <i>Fish Money Food c</i>
    </li>
</ul>

I am new to JQuery, can anybody help me?

Thanks.

NARU
  • 2,769
  • 5
  • 23
  • 28

1 Answers1

2

Something like this? You can use :contains to search for an element that has that text

$('#test').on('keyup', function () {
    $('#myul li').hide();
    $('#myul li:contains("' + this.value + '")').show();
});

DEMO

You can make :contains case insensitive by pasting in this code.

jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});
Community
  • 1
  • 1
Anton
  • 32,245
  • 5
  • 44
  • 54
  • Hi Anton, thanks for the reply. I just updated the HTML code, actually, I only want to search the text in the first most-deepest children element. Can you have a look? – NARU Jan 22 '14 at 15:50
  • @NARU So you shouldn't be able to search test only fish? – Anton Jan 22 '14 at 15:52
  • For example, if the content of one tag is "Fish", the content of other content is "Fish can swim". Then input "Fish" won't work. – NARU Jan 22 '14 at 15:56
  • @NARU It shouldn't work or what do you mean? Show an example in the fiddle – Anton Jan 22 '14 at 16:00
  • I mean in that case, if you input "Fish", then there are two items in the list matching by using your solution. – NARU Jan 22 '14 at 16:03
  • Just one more question: the solution you proposed only works for the list with the structure like "#myul li b". For the list with the structure "#myul li a", you solution doesn't work ( please have a look at the second html code in the problem description ). Do you have an idea how to fix the issue? Thanks. @Anton – NARU Jan 22 '14 at 23:02