0

I am trying to create a “jquery search function” and I want to be able to use more than one word to sort the results.

Can someone please show me how to make it work?

This is what I got:

$(document).ready(function(){

$('.qid').keyup(function() {  
var keyword = $(this).val().toLowerCase().split(" ");

$(".q").removeClass('show');
$(".q:contains('"+ keyword[0] +"'):contains('"+ keyword[1] +"'):contains('"+ keyword[2] +"'):contains('"+ keyword[3] +"')").addClass('show');
if ($('.qid').val() == '')
{
$('.q').removeClass('show');
}
});

});
Hakan
  • 141
  • 4
  • 11

2 Answers2

2

Please, read this: jQuery :contains selector to search for multiple strings

I think this takes your questions about the "contains".

Community
  • 1
  • 1
Cesar
  • 3,519
  • 2
  • 29
  • 43
  • Thanks for the info Cesar :) Tough the problem is only to return all words from the input field. – Hakan Jan 20 '11 at 22:55
0

You can generate the jquery selector string by replacing spaces with the contains Try this:

<script type="text/javascript">
    $(document).ready(function(){  
        $('.qid').keyup(function() {   
            var keyword = $(this).val().replace(/\s+/g, " ").replace(/\s+$|^\s+/g, "");  
            var containsString = keyword;
            $(".q").removeClass('show');
                        containsString = ".q:contains("+containsString+")".replace(".q:contains()","");
            console.log(containsString);
            $(containsString).addClass('show');
            if ($('.qid').val() == ''){
                $('.q').removeClass('show');
            }
        });
});

</script>

Test:

<div>John Resig</div>
<div>George Martin</div>
<div>Malcom Cybernate Sinclair</div>
<div>J. Ohn</div>


<script>
    var baseText = "John Cybernate"
    var containsString = baseText.replace(" ", " ,div:contains(");
    $("div:contains(" + containsString + ")").css("text-decoration", "underline");
</script>

Check the post @: http://www.jsfiddle.net/RUF4P/4/ (Type Lorem Ipsum)

Chandu
  • 81,493
  • 19
  • 133
  • 134
  • Thanks Cybernate, this works. But when I typ in "space" after each word the searchfunction removes the class from all divs, and the divs ad hidden... It's a good start! – Hakan Jan 20 '11 at 22:51
  • My bad, actually it doesn't work. Will try some more and update the question. – Hakan Jan 20 '11 at 23:54
  • I have updated the post and also posted a link to jsfiddle. Try this: http://www.jsfiddle.net/RUF4P/4/ – Chandu Jan 21 '11 at 00:08