Gustavo Henrique
Gustavo Henrique

Reputation: 138

Search for Text inside div

The problem is: I have one div that wraps all my users list. I want to make a search box, but i don't want to use Ajax, so i started trying JQuery, for search the text inside the div and hide the another results. I've tried but i'm stucked on this:

    //Search Box 
$(document).on('input', "#search-weeazer", function(e){
    console.log('input ativado')
    if($(this).val().length >= 4){
        // if($('#colmeia-chat').html().indexOf($(this).val()) > -1){
        //      console.log('Found')
        // } else {
        //      console.log('Not Found')
        // }
        $('div.chat-users>div').each(function(i,div){
            if($(div).html().indexOf($(div).val()) > -1){
                console.log($(div).html() + ' found: ' + i);
            } else {
                console.log("Not Found")
            }

        });
    }


});

Someone know how i can do this? Thanks!

In my HTML i have this:

<div class="chat-users" style="height: 400px;">
            <?php include_once('user-chat-list.php'); ?>
        </div>

Inside "chat-users" i have a list with all users, loaded with php

Here is more HTMl to show the structure: https://jsfiddle.net/jdqbnz2w/

Upvotes: 0

Views: 2997

Answers (1)

KevBot
KevBot

Reputation: 18888

After Question Edit

Here is an updated JSFiddle based on the JSFiddle you included showing how to implement the search with your particular use-case:

JSFiddle


Original Answer:

You're missing some pertinent information in your question, such as "what does the HTML look like that comes from user-chat-list.php?" And because of that it makes it hard to understand exactly how your code applies.

Nevertheless, here is a simple example upon what you have provided that you can modify that does what you are looking for. You can run the following code snippet to see a working example:

var $searchBox = $('#search-weeazer');
var $userDivs = $('.chat-users div');

$searchBox.on('input', function() {
  var scope = this;
  if (!scope.value || scope.value == '') {
    $userDivs.show();
    return;
  }

  $userDivs.each(function(i, div) {
    var $div = $(div);
    $div.toggle($div.text().toLowerCase().indexOf(scope.value.toLowerCase()) > -1);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search:
<input id="search-weeazer">

<p>Users:</p>
<div class="chat-users">
  <div>Tony</div>
  <div>Amber</div>
  <div>Ronald</div>
</div>

Upvotes: 2

Related Questions