populate dropdown on selection of other dropdown

前端 未结 4 615
一整个雨季
一整个雨季 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:51

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

    for HTML:

    
    
    

    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 += ""
        })
        $('#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 })
    

提交回复
热议问题