Reputation: 1159
I am modifying a jQuery autocomplete so that it passes a second term to the search feature to narrow the search. The problem I am having is being able to concatenate the city on to the URL
$(function() {
var city = $('#city').val(); //get the city value from text field
var source = 'search.php?city='; //URL where the search takes place
//autocomplete
$(".auto").autocomplete({
source: source+city , //concatenation not working.
minLength: 1
});
});
I have tried different ways to concatenate the city name onto the url
$(function() {
//var city = //$('#city').val();
var source = 'search.php?city=';
//autocomplete
$(".auto").autocomplete({
source: source+$('#city').val(),
minLength: 1
});
});
I know that the
var city = 'Austin'
works. I am unsure of the
$('#city').val()
Because if I can hard code it in then the same should work for the function to get the variable from the text field. Right?
The text fields are like this
<form action='' method='post'>
<p><label>Pharmacy Names : </label><input type='text' name='names' value='' class='auto'></p>
<p><label>City : </label><input type='text' name='city' id='city' value='' placeholder='Enter City First'></p>
</form>
Even this post Add form value to end of url - Jquery agrees with what I am thinking
This post Get the value in an input text box shows that I am using the correct jquery call to get the textbox value. It just seems like it should be working but it is not.
Upvotes: 0
Views: 934
Reputation: 6263
The behavior of your script is truly correct. This is happened, because when your script initialized, the city
input is empty.
You should attach an event handler to your city
input, and whenever the user type something on that, change the source
of your autocomplete:
$(function() {
// initialize the autocomplete
var source = 'search.php?city=';
$(".auto").autocomplete({
source: source,
minLength: 1
});
// event handler for yout input
$('#city').on('input', function (e) {
var city = this.value;
// set the new source to your autocomplete
// based on jQuery UI Autocomplete
// http://api.jqueryui.com/autocomplete/#method-option
$('.auto').autocomplete( "option", "source", source+city);
});
});
Upvotes: 1
Reputation: 1159
This is what worked for me to be able to use two textboxes to pass two variables to the sql query.
$(function() {
//Pharmacy autocomplete
$("#pharm").click(function() {
var city = $("#city").val();
var str = "../../library/ajax/pharmacy_autocomplete/search.php?city="+city;
//autocomplete
$(".pharmacy").autocomplete({
source: str,
minLength: 1
});
});
});
The #pharm text box is where the click will occur after filling in the city text box. I brought the auto complete inside this function that I did not have to pass the city value to the auto complete. Now I could just concatenate city value onto the URL and get my second value to the search.php.
Upvotes: 0