2010-11-10 84 views
0

我有一個接收JSON響應的頁面。如果JSON中有多個選項,它會根據更長的長度使用Javascript中的for循環動態生成一些單選按鈕。jQuery動態生成單選按鈕,然後傳遞值繼續按鈕

喜歡的東西

for (var i = 0; i < length; i ++){ 
    alert(i); 
     //draw the HTML radio buttons based on the data i++ 
    } 
     //value from radio button button gets passed to a continue button 

什麼會做,在jQuery的最佳方法是什麼?

回答

0

喜歡的東西

for (var i in json) { 
    var input = $('<input>', { 
    type: 'radio', name: 'group-name', 
    value: json[i], 
    'class': 'my_radio' 
    }); 
    $('body').append(input); 
} 

$('#continue').click(function() { 
    var selected = null; 
    $('input.my_radio').each(function() { 
     if ($(this).attr('selected')) 
      selected = $(this).val(); 
    }); 
    // do something with selected.... 
}); 

你有一個表單元素包圍它,如果你需要的。順便說一下,我沒有測試過這個。