0

I want to autocomplete 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!

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

perfect. that worked. Thanks!And you're right, I didn't need to destroy it.
0

Try this one

    $("#city").unautocomplete().autocomplete(

              base_url+"index.php/index/autocompletecities/", 

              {

               extraParams:                 
                   {country:$('#country').val()} 

});

1 Comment

doesn't seem to work. Looking at Firebug, it says "unautocomplete is not a function". For what it's worth, I'm using jQuery 1.5.2 and jquery ui 1.8.12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.