2013-03-07 16 views
1

我努力使兩個相互依存的下拉列表的代碼,我需要一些幫助:爲兩個相互依存的下拉jQuery代碼列出

// Question 1 
    var test1 = ['|Please Select','1|1','2|2','3|3'] 

    // Question 2 

    var test2 = [] 
    var test2a = ['|Please Select','1a|1a','2a|2a','3a|3a'] 
    var test2b = ['|Please Select','1b|1b','2b|2b','3b|3b'] 
    var test2c = ['|Please Select','1c|1c','2c|2c','3c|3c'] 

    // Set the options from Question 1 using the values from the array test1 

    val = "test1"; 
    function add_options(val){ 
     arr = window[val]; 
     var the_id = "#"+val; 
     $.each(arr, function(key,val){ 
      options = val.split('|'); 
      $(the_id).append(
       $('<option></option>') 
       .val(options[0]) 
       .html(options[1]) 
      ); 
     }); 
    } 

這裏我需要幫助

當上的選項,用戶點擊從test1中獲取選定的選項。

瞭解所選擇的選項,然後我可以建立數組問題2:

if(selected == "1"){ 
     var test2 = test2a; 
    } else if (selected == "2") { 
     var test2 = test2b; 
    } else if (selected == "3") { 
     var test2 = test2c; 
    } 

    val = "test2"; 
    function add_options(val){ 
     arr = window[val]; 
     var the_id = "#"+val; 
     $.each(arr, function(key,val){ 
      options = val.split('|'); 
      $(the_id).append(
       $('<option></option>') 
       .val(options[0]) 
       .html(options[1]) 
      ); 
     }); 
    } 

希望大家CA幫助!

+0

你的問題還不是很清楚.. – Bill 2013-03-07 11:58:17

+0

我很抱歉,我不是英語母語,我不知道該怎麼解釋這更好的。想象兩個相互依賴的下拉列表。當用戶從第一個列表中點擊一個選項時,第二個列表將被填充一組選項。如果用戶點擊第一個列表中的不同選項,則第二個列表將填充一組不同的選項。這些選項是從上面的數組中生成的。 – user2065483 2013-03-07 12:02:22

+0

它看起來像你的代碼應該工作,是什麼問題? – Bill 2013-03-07 12:07:01

回答

1

試試這個(編輯):

// Question 1 
var test1 = ['|Please Select', '1|1', '2|2', '3|3'] 

// Question 2 
var test2 = []; 
var test2a = ['|Please Select', '1a|1a', '2a|2a', '3a|3a']; 
var test2b = ['|Please Select', '1b|1b', '2b|2b', '3b|3b']; 
var test2c = ['|Please Select', '1c|1c', '2c|2c', '3c|3c']; 

// Set the options from Question 1 using the values from the array test1 
function add_options(val) { 
var arr = window[val]; 
var the_id = "#" + val; 
$(the_id).text(""); 
$.each(arr, function (key, val) { 
    var options = val.split('|'); 
    $(the_id).append(
      $('<option></option>') 
      .val(options[0]) 
      .html(options[1]) 
     ); 
}); 
} 

$(document).ready(function() { 
var val = "test1"; 
add_options(val); 
$("#test1").change(function() { 
    var selected = $(this).val(); 
    if (selected == "1") { 
     test2 = test2a; 
    } else if (selected == "2") { 
     test2 = test2b; 
    } else if (selected == "3") { 
     test2 = test2c; 
    } 

    val = "test2"; 
    add_options(val); 
}); 
}