开发者

Dropdown list where options populate a second list js/php?

I have a 2 dropdown lists side by side. When user selects from the first list, i need the second list's options to be displayed.

The sub-options will be retrieved from a database. I have a page that will return the necessary html given the specific parent. I just need the first list's selection to trigger an update of list #2.

Whats the best way of accomplishing this?

<select id="parent" name="list1">
    <option value="1">Parent 1</option>
    <option value="2">Parent 2</option>
    <option value="3">Parent 3</option>
    <option value="4">Parent 4</option>
</select>

<select id="child" name="list2">
</selec开发者_如何学JAVAt>

caveat: cant use a form, cause the selection's are part of another form.


The normal way to do this is to do an AJAX request after the first dropdown is selected to retrieve the contents of the second.

Exactly how you do that will depend on the frameworks/libraries you're using, but here's an example of a jQuery plugin designed for it:

jQuery cascade plugin

There's also a number of related questions on SO that may help:

https://stackoverflow.com/search?q=cascading+dropdown


Use the event onchange of the select to call an ajax function to retrieve the new data


A dead simple way is to set up your script to output the entire markup of the generated select list, and inject that into a wrapper element, e.g.:

<div id="wrapper">
    <select id="child" name="list2">
    </select>
</div>

$("#parent').change(function() {
    $('#wrapper').load('getSelect.php','selection=' + $(this).val());
    return false; // may or may not be needed
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜