jQuery: Show only content which contains search values

折月煮酒 提交于 2019-12-13 04:37:58

问题


I want to show only divs that contains the entered search values. So if I type upload login in the Searchbox it should show only Question 1 and Question 3.

Note: It should work with multiple search input values(like in the example: should search for value upload AND login and show the divs which contains this values).

Note 2: It should also show Question 1 and Question 3 if the search input is like this: upl log

Note 3: Not case sensitiv. So upload should filter the div(Question 1) with content Upload.

This is what i got:

<section id="content">
<div id="search-block">
    <input type="text" id="inpSearch" placeholder="Search.." />
</div>
<div>
    <div class="wrapper">
        <h1>Question 1</h1>
        <p>Harry Markus Upload</p>
    </div>
</div>
<div>
    <div class="wrapper">
        <h1>Question 2</h1>
        <p>Registration Append August Download</p>
    </div>
</div>
<div>
    <div class="wrapper">
        <h1>Question 3</h1>
        <p>Login July Dad</p>
    </div>
</div>

$('#inpSearch').keyup(function(){
    var sSearch = this.value;
    $('section#content > div:not(:first-child)').hide();
    $('section#content > div:contains("' + sSearch + '"):not(:first-child)').show();
});

回答1:


Here you have two problems.

  1. You need to use case insensitive jQuery :contains selector. For eg: If you search for upload or Upload it should fetch results.

CODE:

 jQuery.expr[':'].Contains = function(a, i, m) {
             return jQuery(a).text().toUpperCase()
                 .indexOf(m[3].toUpperCase()) >= 0;
           };
           jQuery.expr[':'].contains = function(a, i, m) {
             return jQuery(a).text().toUpperCase()
                 .indexOf(m[3].toUpperCase()) >= 0;
           };

SOURCE: Is there a case insensitive jQuery :contains selector?

2.Split the search string and parse using .each like:

CODE:

    $('#inpSearch').keyup(function(){
    var sSearch = this.value;
    sSearch = sSearch.split(" ");
    $('section#content > div:not(:first-child)').hide();
    $.each(sSearch, function(i){
    $('section#content > div:contains("' + sSearch[i] + '"):not(:first-child)').show();
    });
});

DEMO FIDDLE




回答2:


Try this

    $('#content div').not("#search-block").hide();
$('#inpSearch').on('keyup',function(){
    $('#content div').not("#search-block").hide();
    var val = this.value;
    val = val.split(" ");
    var contains="";
    for(var i = 0; i < val.length;i++){
        contains.length >0?contains+=",div":"";
        contains+=":contains('"+val[i]+"')";
    }
    $('#content div'+contains).show();
});

DEMO

For case sensitive take a look at this



来源:https://stackoverflow.com/questions/18874266/jquery-show-only-content-which-contains-search-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!