2011-03-16 225 views
-1

如何從下拉菜單中進行選擇,以便在下一個下拉菜單中顯示所需的值?下拉選擇

回答

0

這是一個使用Jquery和包含下一個列表選項的JSON對象的例子。這些選項可以通過Ajax加載或通過服務器端代碼(PHP等)嵌入到頁面中。

希望這會有所幫助。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
<script type="text/javascript"> 

// Options JSON object can be created by server side or loaded via Ajax 
var nextOptions = {options1: {"1": {name: "secondOptions1-1", value:"1"}, "2": {name: "secondOptions1-2", value:"2"}}, options2: {"1": {name: "secondOptions2-1", value:"1"}, "2": {name: "secondOptions2-2", value:"2"}}, options3: {"1": {name: "secondOptions3-1", value:"1"}, "2": {name: "secondOptions3-1", value:"2"}}}; 


$(document).ready(function(){ 

// Add event Listener 
$('#list1').change(function(){ 

      // Clear the Second List 
      $('#list2').empty(); 
      // Create an Empty Option 
      $('#list2').append('<option></option>'); 
      // Get Value from first list 
      var value = $('#list1 option:selected').val(); 

       // Cycle through options for second list, and add them. 
       $.each(nextOptions["options" + value], function(index, optionsIndex){ 
     $('#list2').append('<option value="' + optionsIndex["value"] + '">' + optionsIndex["name"] + '</option>'); 
          }); // For Each Loop 

          }); // Event Listener 
}); // Document Ready 
</script> 

<select id="list1"> 
<option></option> 
<option value="1">option 1</option> 
<option value="2">option 2</option> 
<option value="3">option 3</option> 
</select> 
<br /><br /> 
<select id="list2"> 
<option></option> 
</select>