views:

486

answers:

4

i have google this option many days but i did't find it.

what i want is:

  1. I have two Select BOX
  2. First Select box Have Country Names
  3. Second Select Box is Empty

what i want is when i select any country (i.e United Kingdom) from first select box, a php query should run to get all cities name from table then add them to second select box using Jquery.

Thanks

A: 

try this.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;

<script type="text/javascript">
    function moveItem() {
        $("#target").append($("#source").find(':selected'));
    }
</script>

<select id="source" size="3">
    <option>option1</option>
    <option>option2</option>
    <option>option3</option>    
</select>

<button onclick="moveItem()">Move Item</button>

<select id="target" size="3"></select>
Lance Rushing
+3  A: 

Assumption

  • You have a script ("/getCities.php") that takes a parameter ("country") that is the ID of the country you want the cities of and outputs JSON that looks like this:

    {"Cities":
    [
     {
      "ID": 1,
      "Name": "New York"
     },
     {
      "ID": 2,
      "Name": "Los Angeles"
     }
    ]}
    

    (You can use JSONLint to validate your JSON.)

Then maybe something along these lines:

<select id="Countries">
    <!-- omitted -->
</select>
<select id="Cities"></select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
  $(document).ready(function() {
    // when a new country is selected...
    $("#Countries").change(function() {
      // ...clear existing cities...
      $("#Cities").empty();
      // ...and repopulate cities based on JSON data.
      $.getJSON( "/getCities.php",
      // pass the selected country ID
        {
          country: $("#Countries").val()
        },
        function(data) {
          $.each(data.Cities, function(n, city) {
              // add a new option with the JSON-specified value and text
              $("<option />").attr("value", city.ID).text(city.Name).appendTo("#Cities");
          });
        }
      );
    }); // $("#Countries").change(function() { ... });
  }); // $(document).ready(function() { ... });
</script>
Lobstrosity
Thanks, Lovely Ans for what i was looking for...Once Again Thanks you vary much
air
A: 

A few thoughts:

  • Your server-side code should cache city-lists
  • Your client-side javascript should cache query results
  • You should preload your page with cities for the 2 or 3 most-selected countries

Between them, these measures will greatly reduce the number of server callbacks and database hits.

Hugh Bothwell
A: 

The "cascading dropdown" is such a common interface - I find it hard to believe that you couldn't find any examples. Here's a PHP example that will point you in the right direction.

Peter J