jquery go to search page when user clicks on auto completed search results?
I have the following jquery script which performs an auto complete search for my user when they type in the search bar like so:
<script>
$(function() {
var availableTags = [
"Telehandlers",
"Cranes",
"Fork Attachments",
"Aggreko",
"12 Tonne Telhandlers",
"Marwood",
"Crane Suppliers in Manchester",
"Total",
"Oil, Gas & Lubricants",
"Tomato Plant"
];
$( "#search" ).autocomplete({
source: availableTags
});
window.location.replace("search_results.php");
});
</script>
<input type="text" name="search" class="Search_bar_box" id="search">
So if they start typing in Telhandler this will auto complete and show in a drop down beneath the input text field which a user can click on, this then populates the search bar, what I want is if a user clicks on any of the words in the auto complete field for this to redirect the user to the search results page 'search_results.php' or when they have typed into the input field and hit enter.
The search result that user clicked on or typed in should some how get echoed onto the next page and the results displayed for that query.
I'm only a beginner here so not sure how I would do this, please could someone show me what I would need to do or point me in the right direction. Thanks in advance
Looking at the jQueryUI autocomplete API, there's an event for "select" -- you can add an event handler for it (a function that runs whenever that event occurs), which will direct the user to the search results page when they select an option:
$( "#search" ).autocomplete({
source: availableTags,
select: function( event, ui ) { // This is the event handler for `select` event
// ui.item.value gets you the selected value
// window.location.href navigates to the URL in question;
// can use window.location.replace if you don't want to reflect this in browser history
// See http://stackoverflow.com/questions/1226714/how-to-get-browser-to-navigate-to-url-in-javascript for more on href vs. replace
window.location.href('search_results.php?q=' + ui.item.value);
}
});
You can also bind the submit
action of the form (which will pick up when users hit enter) to do the same thing:
// I've created a `form` tag around this search w/ ID 'searchForm'
$('#searchForm').on("submit", function(event) {
event.preventDefault(); // prevent the default event handler, which reloads the page
window.location.href('search_results.php?q=' + $('#search').val());
});
We are passing a parameter to the PHP script in question here using the ?q=
; this can be retrieved using the $_REQUEST
variable in PHP:
<?php
$strQuery = $_REQUEST['q'];
echo "You searched for $strQuery";
... // Whatever else you want to do ... probably search for things!
?>
To play around a bit more with the autocomplete events, check out this jsFiddle.
链接地址: http://www.djcxy.com/p/42204.html