Reputation: 25
I am new to jquery and am trying to make a live search from my existing search page where you have to press enter.
This is the code I have made so far.
$( document ).ready(function() {
$('#searchhh').on("input", function() {
var searchquery = this.value;
$( "#searchform" ).submit();
});
});
This gets the input of the form and searches it every key stoke. The problem is the text that the user types resets every time the form submits. I tried to post the search value as a get variable and display it as the search bars value and auto focus into the the search bar every time the page reloads, this puts the typing bar at the beginning of the form before what the user has typed.
I feel like I am approaching this the wrong way please help. :)
Upvotes: 0
Views: 117
Reputation: 20590
You need to post your form via ajax. Here's a simple fiddle to demonstrate this:
HTML:
<form id="searchform" method="post" action="some_url_here">
<input type="text" name="search" placeholder="Search..." />
</form>
Results:<br>
<div id="results"></div>
JS:
$('#searchform').on("keyup", "input", function() {
var form_data = $("#searchform").serialize();
var form_url = $("#searchform").attr("action");
var form_method = $("#searchform").attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnOutput){
// Your search results are outputted here
$("#results").html(returnOutput);
}
});
});
Upvotes: 2