javascript - Multipe JQuery Searches in a single page -
i have page have 10 different ul's multiple div's in each li should have each div inside li's searchable. each searchbox should searching it's own ul individually without affecting other ul's in page. solution using replicate search code while incrementing selectors numerically. creates lot of redundancy.
how can limit redundancy , have each search still affect it's own ul?
the following incremented code (only twice instead of 10 sake of brevity):
the html:
<h1>search one</h1> <input type="text" id="search1" value="" placeholder="enter search text" /> <div id="results1"> <ul> <li> <div class="listing-three">apple</div>| <div class="listing-three">banana</div>| <div class="listing-three">cherry</div> </li> <li> <div class="listing-three">apple</div>| <div class="listing-three">banana</div>| <div class="listing-three">cucumber</div> </li> <li> <div class="listing-three">apple</div>| <div class="listing-three">berry</div>| <div class="listing-three">cheese</div> </li> </ul> </div> <h1>search two</h1> <input type="text" id="search2" value="" placeholder="enter search text" /> <div id="results2"> <ul> <li> <div class="listing-three">apple</div>| <div class="listing-three">banana</div>| <div class="listing-three">cherry</div> </li> <li> <div class="listing-three">apple</div>| <div class="listing-three">banana</div>| <div class="listing-three">cucumber</div> </li> <li> <div class="listing-three">apple</div>| <div class="listing-three">berry</div>| <div class="listing-three">cheese</div> </li> </ul> </div>
the jquery
$("#search1").keyup(function() { var searchtext = $(this).val().tolowercase(); $("#results1 li").each(function() { console.log($(this).text()); var string = $(this).text().tolowercase(); if (string.indexof(searchtext) != -1) { $(this).show("slow"); } else { $(this).hide("slow"); } }); }); $("#search2").keyup(function() { var searchtext = $(this).val().tolowercase(); $("#results2 li").each(function() { console.log($(this).text()); var string = $(this).text().tolowercase(); if (string.indexof(searchtext) != -1) { $(this).show("slow"); } else { $(this).hide("slow"); } }); });
i have included fiddle ease of explanation , clarity of functionality.
in input box, give attribute indicate list for
<input type="text" id="search1" value="" placeholder="enter search text" class="searcher" data-search-in="results1"/>
notice last 2 attributes class
, data-search-in
now can refactor code as
$(".searcher").keyup(function() { var searchtext = $(this).val().tolowercase(); var searchin = $(this).attr("data-search-in"); $("#" + searchin + " li").each(function() { console.log($(this).text()); var string = $(this).text().tolowercase(); if (string.indexof(searchtext) != -1) { $(this).show("slow"); } else { $(this).hide("slow"); } }); });
Comments
Post a Comment