Reputation: 3285
I have the following search suggestion script, where as a user types dynamically the result is updated. What I would want is that when a user click on one of the suggestion it takes them to the following:searchPage.php?user_query=what the user has typed in the input
Below is the script:
$(function () {
$(".search").keyup(function () {
var searchid = $(this).val();
var dataString = 'search=' + searchid;
if (searchid != '') {
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function (html) {
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").live("click", function (e) {
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function (e) {
var $clicked = $(e.target);
if (!$clicked.hasClass("search")) {
window.open('searchPage.php?user_query=', '_self', false);
}
});
$('#searchid').click(function () {
jQuery("#result").fadeIn();
});
});
At its current state it just open the window to searchPage.php but doesn't take into account in the url what the user has entered. The desired result is searchPage.php?user_query=what ever you want
Update:
<form method="get" action="searchPage.php" enctype="multipart/form-data" autocomplete="off">
<input type="text" class="search" id="searchid" name="user_query" id="searchBar" placeholder="Search for courses"/>
<input type="submit" id="searchButton" name="search" value="search" class="btn btn-danger" autocomplete="off"/>
<div id="result"></div>
</form>
Upvotes: 0
Views: 297
Reputation: 1
Try
// `searchid` variable available to `keyup`, `click` event handlers
var searchid = "";
var input = $("#searchid");
var results = $("#results");
input.on("keyup", function(e) {
searchid = e.target.value;
results.text(searchid)
});
results.on("click", function(e) {
var popup = window.open("searchPage.php?user_query="
+ searchid, "_self", false);
});
jsfiddle http://jsfiddle.net/hxehczpq/1/
Upvotes: 1
Reputation: 17713
You can get the value of the search string like this:
document.getElementById('searchid').value
So, appending it to your query would look something like this:
window.open('searchPage.php?user_query=' + document.getElementById('searchid').value,'_self',false);
Depending on what is in the search box, you might have some issues to address, such as a search term that includes the &
symbol (e.g. ?user_query=search&find for example would only come across as search on the server) - you don't want to accidentally pass an extra param that you intend to be part of the search string. To address you might convert that character:
var searchString = document.getElementById('searchid').value.replace(/&/g,'&')
window.open('searchPage.php?user_query=' + searchString,'_self',false);
Upvotes: 1