My website features a search box that allows users to search through a database of books. When utilizing the search feature, users are presented with the following options:
- Search Query (a text input field)
- Where to search (a select field with the options: current, archive or all)
- What to search for (a select field with the options: title, author, owner or reader)
As users type in the search field, suggestions for book titles appear below similar to Google's search feature. I am seeking guidance on how to determine which search option they have selected (e.g., title, author) and display relevant suggestions accordingly.
Below is the current code snippet I am using:
HTML
<form method='get' action='/main'>
<label for='search'>Search</label>
<div style='position:relative;display:inline;'>
<input type='text' id='search' name='search' onkeyup='showHint(this.value)' autocomplete='off'/>
<div style='display:inline;' id='txtHint'></div>
</div>
<select name='searchIn'>
<option name='searchIn' id='searchIn' value='current' selected>Current</option>
<option name='searchIn' id='searchIn' value='archive'>Archive</option>
<option name='searchIn' id='searchIn' value='all'>All</option>
</select>
<select name='searchBy' onChange='getSearchBy(this.value)'>
<option name='searchBy' id='searchBy' value='Title' selected>By Title</option>
<option name='searchBy' id='searchBy' value='Author'>By Author</option>
<option name='searchBy' id='searchBy' value='Owner'>By Owner</option>
<option name='searchBy' id='searchBy' value='Reader'>By Reader</option>
</select>
<input type='submit' class='submit' value='Submit'/>
</form>
AJAX/Javascript
function getSearchBy(val){
return val;
}
function showHint(str){
var xmlhttp;
if (str.length==0){
document.getElementById('txtHint').innerHTML='';
return;
}
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('txtHint').innerHTML=xmlhttp.responseText;
}
}
var searchBy = getSearchBy(document.getElementById('searchBy').value);
xmlhttp.open('GET','get_hint.php?q='+str+'&searchBy='+searchBy,true);
xmlhttp.send();
}
The 'get_hint.php' file handles the processing, queries the database, and returns the results as the innerHTML of the txtHint element...
Despite implementing the getSearchBy function, it seems to not return 'Author' when the 'By Author' option is selected. Any insights on this issue?
Update
I appreciate all the responses provided, and I have marked the quickest one as the correct answer. Thank you to everyone for the prompt assistance!