Jquery UI autocomplete - using value from a previous select field
I want to autocomple开发者_如何学JAVAte a Cities text input, but only search for cities in the country that was previously selected. The code I have seems like it should work, but it's not sending the correct country value.
The form:
Country: <select name='country' id='country'>
<option value='US'>USA</option>
<option value='UK'>United Kingdom</option>
</select><br/>
City: <input type='text' name='city' id='city' />
The js:
$( "#city" ).autocomplete({
source: "searchCities/" + $('select#country option:selected').val(),
minLength: 2
});
The URL structure should be 'searchCities/UK?term=foo' and the SQL statement is searching for the value of 'term' where the country code is 'UK'. If I type in the URL manually, it works without a problem (limiting to only the country)... and the autocomplete works in the form. However, it returns ALL cities without limiting by the country code.
Is there something I may be missing? Or maybe a better way to accomplish this? Thanks!
If you are not doing so already - you should modify the autocomplete's source attribute each time the select box's selected value is changed.
you can destroy and re-build the autocomplete every time the user selects a new value into the select box:
<script>
function renewAutocomplete() {
$( "#city" ).autocomplete("destroy");
$( "#city" ).autocomplete({
source: "searchCities/" + $('select#country option:selected').val(),
minLength: 2
});
}
</script>
Country:
<select name='country' id='country' onchange='renewAutocomplete();'>
<option value='US'>USA</option>
<option value='UK'>United Kingdom</option>
</select>
<br/>
City: <input type='text' name='city' id='city' />
or maybe it is better not to destroy it and re-build it, rather modify its source attribute:
<script>
function renewAutocomplete() {
$( "#city" ).autocomplete("option", "source", "searchCities/" + $('select#country option:selected').val());
}
</script>
Try this one
$("#city").unautocomplete().autocomplete(
base_url+"index.php/index/autocompletecities/",
{
extraParams:
{country:$('#country').val()}
});
精彩评论