Search code examples
javascriptjqueryhtmlcssmaterialize

Reorder divs after search


I created simple function that searches through divs and shows searched one. However I am not able to reorder them. It just hides the ones that doesn't equal to the user entered text.

I am using materializecss grid system like this and it has lots of cards:

<div class="row">
<div class="col s12 m4">
   <div class="card samll">
      <div class="card-image waves-effect waves-block waves-light teal lighten-1">
         <img class="activator" src="https://...">
      </div>
      <div class="card-content">
         <span class="card-title activator grey-text text-darken-4">Skruf<i class="material-icons right">more_vert</i></span>
         <p><a id="id" class="aaf"  onClick="reply_click(this.id)">Button</a></p>
      </div>
      <div class="card-reveal">
         <span class="card-title grey-text text-darken-4">Some Title<i class="material-icons right">close</i></span>
         <p>Some longer text.</p>
      </div>
   </div>
</div>

And this is how I am searching through the divs:

$('#brandSearch').keyup(function() {
    var valThis = $(this).val().toLowerCase();
    if (valThis == "") {
        $('.card').show();
    } else {
        $('.card').each(function() {
            var text = $(this).text().toLowerCase();
            (text.indexOf(valThis) >= 0) ? $(this).show(): $(this).hide();
        });
    };
});

You can see the working demo here.


Solution

  • You need to hide parent element of the element which you are hiding now

    $('#brandSearch').keyup(function() {
        var valThis = $(this).val().toLowerCase();
        if (valThis == "") {
            $('.card').show();
        } else {
            $('.card').each(function() {
                var text = $(this).text().toLowerCase();
                (text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
            });
        };
    });

    Here is your modified JS, I hope it will work.