I'm trying to implement a search bar on my website. I already have the back end processing working correctly, and I have the html and CSS in place for the search bar, all I have left to do is get my JavaScript to trigger the search to execute. Here is the html for the search bar:
<div id="search_field_container">
<input type="text" name="search_field" id="search_field" maxlength="100" placeholder="Search by item name or #tag" value="Search by item name or #tag" onclick="value=''" />
<button id="search" name="search_button">s</button>
</div>
What I'm trying to do is set up jQuery event handlers to trigger a JavaScript function called search when the user either presses enter while the text bar is focused or when they click the search button. However, I absolutely cannot seem to get the event handlers to trigger. Here is my JavaScript:
//Search function
$(document).ready(function(){
console.log("In anonymous function.");
$("#search").on('click', function(event){
alert("In click handler");
search();
});
});
$("#search_field").bind('keyup', function(event){
alert("In keyup handler");
if(event.keyCode == 13){
alert("In enter handler");
search();
}
});
function search(){
alert("Something happened!");
var searchTerm = $("#search_field").val();
alert("You're trying to search for "+searchTerm);
}
Currently, nothing happens when I either hit enter with the cursor in the text bar or press the search button. I know it isn't JavaScript errors preventing execution of everything, because all of the other JavaScript on the page executes perfectly fine.
I know the search function works and that the at least the search_field
id on the text input is correct because if I add an onclick
to the button and call search through that, it executes correctly and it always echoes the value from the text field correctly.
The search bar is in a separate header file so I don't have to include it in the html of every page, but that shouldn't make a difference because I'm including the file with PHP, so it should already be in place before the file even gets to the user. Just in case though, I've already tried using .bind
and document.ready
as you can see, as well as .on
and an anonymous wrapper function, to no avail.
I don't get any error messages in the console or anything, it just silently fails. I know there are tons of similar questions on this site, but I've already tried every solution I could find to about a dozen of them. If anyone knows what the problem is and how to fix it, or even just additional tests to help figure out why this is failing so I can narrow my searches down, that would be greatly appreciated.
EDIT: Huangism created this JSfiddle using my code and showed that the code works properly, so there must be something about the context of my site causing it to not function.
Fiddle - http://jsfiddle.net/3m5Mp/