I am very very new to JQuery and Javascript. I have implemented autocomplete functionality that retrieves the data from remote datasource( Mysql + PHP) using jQuery Demo. I am stuck at the part where the mysql query triggered by the php script is binded to the drop down menu option.
So if I select "comments" from one of the option value, how do I bind it to the search textbox with id="search_term".
<label>Select Search parameter:
<select id="search_parameter" name="search_parameter">
<option value="Sample name">Sample Name</option>
<option value="Location name">Location Name</option>
<option value="comments">Comments</option>
</select>
</label>
<label> Search Term:<input type="text" id="search_term" required name="search_term" maxlength=30></label>
Now if I select option value as "comments" it should trigger the PHP script that queries the comment field. But I am not sure how do I get the conditional statement into JQuery. I am not getting success with
$(function(){
$('#search_parameter').change(function(){
if (this.value == "comments") {
jQuery(document).ready(function($){
$('#search_term').autocomplete({source:'search_comments.php', minLength:2});
});
else if( this.value =="Sample name") {
jQuery(document).ready(function($){
$('#search_term').autocomplete({source:'search_sample_name.php', minLength:2});
});
}
I am not sure if this is the right approach. I apologize if this question is not worthy of stackoverflow.com. Thank you
I would recommend initializing the autocomplete widget once on the input
. You can use the option
method to set the source
when the value of the select
element is changed:
$(function () {
$("#search_term").autocomplete({
source: "",
minLength: 2
});
$("#search_parameter").change(function () {
if (this.value === "Sample name") {
$("#search_term").autocomplete("option", "source", "search_sample_name.php");
} else if (this.value === "comments") {
$("#search_term").autocomplete("option", "source", "search_comments.php");
}
}).change(); // Trigger the "change" event to set the source correctly the first time.
});
You can make this even more robust by using a data-*
attribute on each option that indicates which source to use:
HTML:
<label>Select Search parameter:
<select id="search_parameter" name="search_parameter">
<option value="Sample name" data-autocomplete="search_sample_name.php">Sample Name</option>
<option value="Location name" data-autocomplete="search_locations.php">Location Name</option>
<option value="comments" data-autocomplete="search_comments.php">Comments</option>
</select>
</label>
JavaScript:
$(function () {
$("#search_term").autocomplete({
source: ''
});
$("#search_parameter").change(function () {
var selectedSource = $(this).find("option:selected").data("autocomplete");
$("#search_term").autocomplete("option", "source", selectedSource);
}).change();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With