简体   繁体   中英

How to hide divs when livesearching with jQuery

I'm trying to make a function in jQuery that, while typing, it livesearch divs with the same h5 element (I know it could be a class or an id , but I'm making it like that because reasons). And when the searchbox is empty again, everything should be back to normal.

I'm using Bootstrap panels to achieve this also.

My jQuery code is this. I got it from another answer here, but modified a little for me needs:

//Se supone que busca. Lo plagié vilmente.
$("#busqueda").keyup(function(){

// Retrieve the input field text and reset the count to zero
var filter = $(this).val();

// Loop through the comment list
$(".nombre").each(function(){

    // If the list item does not contain the text phrase fade it out
    if ($(this).attr("h5").contains(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();

        alert(filter);

    // Show the list item if the phrase matches and increase the count by 1
    } else {
        $(this).show();
    }
});
});

My HTML code is:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 p1" data-clickstate="0">
            <div class="panel panel-default" id="panel_1">
                <div class="panel-body" style="display: inline" id="cat_1">

                    <div class="icono">
                        <img src="media/iconos/motores_busqueda.png" alt="">
                    </div>
                    <div class="nombre-y-des">
                        <div>
                            <h5 class="nombre">Motores de búsqueda</h5>
                        </div>
                        <div class="des">
                            <p>Servicios de búqueda de páginas web.</p>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <div class="col-sm-4 col-md-4">
            <div class="panel panel-default" id="panel_2">
                <div class="panel-body" id="cat_2" style="display: inline">
                    <div class="icono">
                        <img src="media/iconos/navegadores.png" alt="">
                    </div>
                    <div class="nombre-y-des">
                        <div>
                            <h5 class="nombre">Navegadores</h5>
                        </div>
                        <div class="des">
                            <p>Programa que permite navegar por internet, renderizado páginas HTML en contenido visual y
                                comprensible.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-4 col-md-4">
            <div class="panel panel-default" id="panel_3">
                <div class="panel-body" id="cat_3" style="display: inline">
                    <div class="icono">
                        <img src="media/iconos/servidores_correo.png" alt="">
                    </div>
                    <div class="nombre-y-des">
                        <div>
                            <h5 class="nombre">Servidores de correo</h5>
                        </div>
                        <div class="des">
                            <p>Servicio que permite enviar y recibir mensajes mediante sistemas de comunicación eletrónicos
                                en línea.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

The jQuery code should be looking the h5 attribute to compare it with what is being typed, and therefore hide all other divs. Tho I think I'm missing something or I'm doing it all wrong. I'm not that experienced with jQuery.

This is the searchbox:

<div id="contenido">
    <div class="container">
        <div class="row" id="busqueda">
            <div class="col-md-12 text-center ">
                <div id="custom-search-input">
                    <div class="input-group col-md-12">
                        <input type="text" class="form-control input-lg" placeholder="Actividad a realizar, categorías, etc. (no olvides escribir los acentos correctamente ;~)"
                            id="inputBusqueda" />
                        <span class="input-group-btn">
                            <button class="btn btn-info btn-lg" type="button">
                                <i class="glyphicon glyphicon-search"></i>
                            </button>
                            </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

attr("h5") isn't going to work, and you don't need it because you've already selected the h5 elements with the class "nombre".

contains() may not do what you think it does. it's for checking parent/child relationship in the DOM (you may be confusing it with :contains )

To get the text of the nombre elements use just

$(this).text()

or

$(this).html()

Then run your regex on that.

 // Case insensitive :contains | https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/ $.expr[":"].contains = $.expr.createPseudo(function(arg) { return function(elem) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); $(document).ready(function() { //Se supone que busca. Lo plagié vilmente. $("#inputBusqueda").keyup(function() { // Retrieve the input field text and reset the count to zero var filter = $(this).val(); // Loop through the comment list $(".col-sm-4.col-md-4").each(function() { if ($(this).find('h5').is(':contains("' + filter + '")')) { $(this).show(); } else { $(this).hide(); } }); }); }); 

  • Extra: the first thing is an snippet I found because I think users tend to search in lowercase; and it allows to search with insensitive case.
  • Changed the id of the search input ( #inputBusqueda ).
  • Redid all the "contains" part. In your code you were using $.contains() but like @Stu Cartwright said it's used for comparing element relations and such.
  • The way I did it is simple: for each "column" we check if an h5 child :contain s the filter value, if so we show it, else we hide it.

Check JSFiddle demo . Also if you want the search to be case sensitive, just get rid of the first part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM