I have created a search function for my Site and originally just had it set up as a Form Element
using POST
to send the variable to my search page. However, this would just give me a plain URL at search.php
. So if the clicked on something and then went back there would be no posted variable so no more search results.
I wanted to improve this so if they click on something and go back it will be going back to the URL of search.php?term=search%20term
which will then treat it as a GET
variable so it will show the results again and it can be used to go search for something directly in the URL bar.
(NOTE: I have rewrite rules to change search.php?term=search%20term
to search/search%20term
. I also have two search bars one displayed for mobile and one for desktop)
So I changed my code to the following:
function search(x){
if(x=="search"){
var search_term = document.getElementById('searchbox').value;
}else if(x=="mini_search"){
var search_term = document.getElementById('minisearchbox').value;
}
if(search_term != ""){
window.location.href = "search/"+search_term;
}
}
<div id="search">
<input type="text" placeholder="Product Search" name="search" id="searchbox">
<input type="image" src="media/search.png" class="search_button" name="search_button" onclick="search('search'); return false;">
</div>
<div id="minisearch">
<input type="text" placeholder="Product Search" name="search" id="minisearchbox">
<input type="image" src="media/search.png" class="search_button" name="search_button" onclick="search('mini_search'); return false;">
</div>
This is working fine as expected but obviously now with the return false
statement it won't search when a user presses enter
which I want them to be able to do.
So I tried adding the following code:
document.getElementById('searchbox').addEventListener('keypress', function(key){
if(key.keycode==13){
search(search);
}
});
document.getElementById('minisearchbox').addEventListener('keypress', function(key){
if(key.keycode==13){
search(mini_search);
}
});
However, I now get the error saying Uncaught TypeError: Cannot read property 'addEventListener' of null
and I am not sure what could be causing this.