August 09, 2017
Check all values of a div, by class name, and return only values matching the search criteria. Below is an example where this search filter is applied to a staff directory.
HTML:
<input type="text" id="search_input"/> <input type="button" id="search_button" value="search"/>
PHP:
$args = array( 'role' => 'subscriber', 'orderby' => 'user_nicename', 'order' => 'ASC' ); $subscribers = get_users($args1); foreach ($subscribers as $user) { ?> <div class="staff_member"> <h3><?php echo $user->display_name; ?> - <span><?php the_field('title', 'user_' . $user->ID); ?></span></h3> <?php the_content(); ?> </div> <?php } ?>
jQuery:
jQuery('#search_button').click(function(){ jQuery('.staff_member').hide(); var txt = jQuery('#search_input').val(); jQuery('.staff_member').each(function(){ if(jQuery(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1){ jQuery(this).show(); } }); });
Sourced here. JSFiddle link.
Allow searching to be triggered by pressing the ENTER key via keyboard with this addition:
jQuery('#search_input').on('keypress', function(e) { if (e.keyCode === 13) { jQuery('#search_button').click(); } });