简体   繁体   中英

drop down list in html form

consider that there are two drop down list in a html form.

The first list named "country" has a list of the countries.

The second list is the "cities" which should be dynamically populated when a country is selected.

How i am supposed to implement this dynamically?

which is the easiest and the simplest possible way to implement this either in javascript or jquery or ajax?

please help with sample codes and ideas so that i will be able to implement it or some external links or tutorials

Using jQuery, use the change event of the first drop down, then update the second, a little like so

$("#country").change(function(){
    //do an ajax request, and update #cities
});

You can do this with pure JavaScript. Implement an onchange attribute in the first select:

<select id="countires" onchange="makeCitiySelect( );"> .. </select

and in the makeCitiySelect( ) function you can read the value of this select with document.getElementsById( "countries" ).value and send create the new select box with the cities of this country.

If the cities of your countries are in a database on the server you have to send an ajax request and get the cities as response..

But for sure, with jQuery you can solve this problem much better

1.- Create the 2 select boxes 2.- Create an onchange js or jquery function on the first select, so every time it gets selected the other select changes 3.- Inside the onchange function make an ajax call to the service which has the corresponding contents for the selected option. 4.- Retrieve the data and rebuild the second select box with the corresponding data.

  1. Apply a onchange event on your country dropdown (http://api.jquery.com/change/)
  2. Send an ajax request to server and get the city list (http://api.jquery.com/jQuery.ajax/)
  3. On success of ajax request, populate the second list "cities". Remember to remove any already populated cities from the cities list.
  4. Store all the cities list which you got from server into an array. When next time the users selects the same country, use data stored in array to display the cities list. This way you don't have to make multiple ajax request for same country.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM