populate dropdown on selection of other dropdown

前端 未结 4 533
一整个雨季
一整个雨季 2020-12-12 05:32

I have two drop-down boxes. I want to populate second drop-down box on selection in the first drop-down box. My values are retrieving from database. Is this possible withou

相关标签:
4条回答
  • 2020-12-12 05:41

    You could do it either way. If you dont want to use ajax, just load every single option into an object. Then when you select something from select #1, populate #2 with the assoicated array of data from your object.

    If I were doing it, I wouldn't do it with ajax unless there was a TON of data.

    0 讨论(0)
  • 2020-12-12 05:41

    Yes you can do it without using php. For that you've to assign two different states list in Javascript array and base on the selection just change the options in the other select box. As simple as that.

    You can assign the javascript array using your serverside scripting language while loading the page if you're using database to store the states.

    But do not do this unless you've very small amount data. In your case you've only 2 countries so you can go ahead with it.

    0 讨论(0)
  • 2020-12-12 05:49

    Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.

    This is the country dropdown:

    <?php
            $countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
            echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
            while($clist=mysql_fetch_array($countrylist))
            {
              echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
            }
            echo "</select>";
     ?>
    

    This is the region dropdown:

    <select name="region" id="region" ></select>
    

    Now make a seperate file named crlist.js and include it in the page having above code like this:

    <script  type="text/javascript" src="crlist.js"> </script>
    

    code for crlist.js:

    var request = false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
    request = false;
    }
    }
    @end @*/
    function fillSelect(country,path) {
    var url = path+"crlist.php?country=" + country;
    request.open("GET", url, true);
    request.onreadystatechange = go;
    request.send(null);
    }
    
    function go() {
    if (request.readyState == 4) {
    //if (request.status == 200) {
    
    var response = request.responseText;
    
    var list=document.getElementById("region");
                for (i = list.length - 1; i>=0; i--) {
                    list.remove(i);
                }
    var records=response.split('|');
    for (i=1; i<records.length; i++) {
        //alert("rcord="+records[i]);
        var record=records[i].split('*');
        var region=record[0];
        //alert("region="+region);
        var regionid=record[1];
        //alert("regionid="+regionid);
        var x=document.createElement('option');
        //var y=document.createTextNode(region);
        x.text=region;
        //x.value=region;
        //alert(x.text);
       //x.appendChild(y);
       //list.appendChild(x);
       list.options.add(x);
       }
      //}
     }
    }
    
    function initCs(path) {
    
    if (!request && typeof XMLHttpRequest != 'undefined') {
    request = new XMLHttpRequest();
    }
    var country=document.getElementById('country');
        country.onchange=function() {
    
            if(this.value!="Select") {
    
                var list=document.getElementById("region");
                for (i = list.length - 1; i>=0; i--) {
                    list.remove(i);
                }
            //while (list.childNodes[0]) {
            //list.removeChild(list.childNodes[0]);
            //}
            }
            fillSelect(this.value,path);
            //alert(this.value);
    
        }
    //fillSelect(country.value);
    }
    

    Now make a seperate file named crlist.php.

    Code for crlist.php:

    <?php
    require_once 'yourconfigfile.php';
    
    $cname = $_GET['country'];
    
    $query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
    $res = mysql_query($query) or die(mysql_error());
    while($region = mysql_fetch_array($res)){
        echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
    }       
    ?>
    

    Now add following script on the page having dropdowns:

    <script  type="text/javascript" src="crlist.js"> </script>
    <script>
    $(document).ready(function() {
    
        initCs("");
    
    });
    </script>
    

    This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.

    Reference to my answer: Cascade Dropdown List using jQuery/PHP

    Hope this helps.

    0 讨论(0)
  • 2020-12-12 05:51

    if you encode your data into JSON format, then you can do something like this:

    for HTML:

    <select name='country' id='country'>
        <option value='india'>India</option>
        <option value='usa'>USA</option>
    </select>
    <select name='dates' id='dates'>
    </select>
    

    jQuery:

    data = {
        india: ['2011-03-11','2010-02-01'],
        usa: ['2006-03-11','2009-02-01']
    }
    
    $('#country').change(function(){
        var dateopts = ''
        $.each(data[$(this).val()],function(i,v){
            dateopts += "<option value='"+v+"'>"+v+"</option>"
        })
        $('#dates').html(dateopts)
    })
    

    Which when the country is changed, will build and populate the options for the second select box.

    See the working example here: http://jsfiddle.net/xHxcD/


    The above method requires all data to be sent to client side with the initial page request. If you have lots of data, it would be better to receive the data via AJAX. It would be simplest to do this by building an object in PHP with the same data structure as your client side, then use json_encode to convert it into as JSON string and echo it out.

    Reading this into your client side would then be as simple as this:

    $.ajax('myJsonData.php?country=india',function(jsonData){ data.india = jsonData })
    
    0 讨论(0)
提交回复
热议问题