Alex V
Alex V

Reputation: 81

Autocomplete city with jQuery

I am using this http://jqueryui.com/autocomplete/#remote-jsonp to make an autocomplete input but, when I want to make like 3x input like this, I can do it only with the first one. Is anyone there to explain me what is the problem that is working only for the first input, for the 2nd, 3rd... is not working, and how to make it working? I just copied this 3 times, and no results...

<div class="ui-widget">
  <label for="city">Your city: </label>
  <input id="city">
  Powered by <a href="http://geonames.org">geonames.org</a>
</div>

Thank you in advance!

Upvotes: 2

Views: 287

Answers (2)

Alon Eitan
Alon Eitan

Reputation: 12025

That's because you have 3 elements with the same id (city) make sure to change the IDs, and use a class selector to select the 3 elements:

<div class="ui-widget">
    <label for="city1">Your city: </label>
    <input id="city1" class="city">
    Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget">
    <label for="city2">Your city: </label>
    <input id="city2" class="city">
    Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget">
    <label for="city3">Your city: </label>
    <input id="city3" class="city">
    Powered by <a href="http://geonames.org">geonames.org</a>
</div>

And change the selector:

$( ".city" ).autocomplete({ ..... });

Upvotes: 1

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

Dont use the Id's!!! use Class selector. When ever you are dealing with multiple elements, use Class selectors to make life easier.So add a common class to all your input elements say city and then your script must be written like below.

$('.city').autocomplete();

Is anyone there to explain me what is the problem that is working only for the first input, for the 2nd, 3rd...

The reason is very simple. When ever you try to access a element by its id Jquery will start looking from the top of the DOM, So the first element it finds it stops the search and returns it (This is because Id's are meant to be UNIQUE). But thats not the case while selecting by class name. Jquery return you all the elements with the given class in the entire DOM.

Upvotes: 1

Related Questions