Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - populate dropdown on selection of other dropdown

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 without using php or I need intermediate ajax and php file to get values from first drop-down and populate values file. Or this is possible without using php I mean only using Jquery. Please give me hint to do that.

Suppose I have 2 countries. First is INDIA and second is USA. ON first drop-down I am selecting countries and if first dropdown is selected than second dropdown populate its respective states.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...