Webster Webster - 1 year ago 98
jQuery Question

Get search box to filter results

I have a list of filter buttons that filter gallery items.
The filtering works well, and the filter state is saved in session storage.
I'm trying to link up the search box and button.

The behavior I'm trying to achieve is when someone types into the search box then hits enter or clicks search button, their entry is passed to the filter function and matching results are shown.

I'm having trouble getting the string and assigning it to a variable.
I'm having trouble getting the filter to work on that variable.

I made a fiddle to demonstrate:

The JS:

$(document).ready(function () {

//declare a global variable

var filterVal;

//check if sessionStorage exists and if so, if there is a var called fillTerm
//if not, set it to a default value (all)
if (sessionStorage && sessionStorage.getItem("filTerm")) {
filterVal = sessionStorage.getItem("filTerm");
} else {
filterVal = "all";
sessionStorage.setItem("filTerm", filterVal);

//now let's attach some interaction to our buttons
$(".filter-button").on("click", function () {
//get the value for our filter
filterVal = $(this).attr("data-filter");
//store it in the session storage
sessionStorage.setItem("filTerm", filterVal);
//call our view update function

//this is the function that manipulates the UI
function updateView() {
//default situation: all is visible
if (!filterVal || filterVal === "all") {
//hide all and show filtered values
else {
$('.filter').filter('.' + filterVal).show();

//update the view when the page loads

$(".searchButton").click(function () {
var term = $(this).attr('data-filter');
var searchTerm = document.getElementById("searchEntry").value;



The searchButton function at the end is what is not working. I realize the button can trigger the function on click or the function can listen for a click on id of the button. In any case I haven't been able to pick up the search input.

The form may need method POST, depends where I ask.

Answer Source

When you click the button, the form is submitted and the page reloads. There is no need to use a form if you can render it all locally.

I have updated the fiddle to remove the form, and added a new click handler. You can add another event listener to handle the enter key and perform the same action.

I couldn't determine from your question whether you required the form to be POSTed or not. It seemed to me that were just looking for client side, hence my answer drops the form.


            filterVal = $('#searchEntry').val();
            sessionStorage.setItem("filTerm", filterVal);

                if (e.keyCode == 13) {
              filterVal = $('#searchEntry').val();
              sessionStorage.setItem("filTerm", filterVal);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download