2012-04-18 45 views
3

我可以得到一些想法或我如何填充單選按鈕的選中狀態(取決於從數據庫加載的數據)的示例?基於json響應選擇單選按鈕

比如我生成從SELECT查詢,看起來像一個數組:

array(
[0] => array( 
    ['note_id'] => 1 
    ['value'] => 'no' 
) 
[1] => array(
    ['note_id'] => 4 
    ['value'] => 'yes' 
) 
[2] => array( 
    ['note_id'] => 5 
    ['value'] => 'yes' 
) 
) 

複選框組樣子:

<input type="radio" name="1" value="yes"> 
<input type="radio" name="1" value="no"> 
<input type="radio" name="1" value="done"> 

<input type="radio" name="2" value="yes"> 
<input type="radio" name="2" value="no"> 
<input type="radio" name="2" value="done"> 

現在使用json_encode我把結果的數據數組:

[{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}] 

我通過這些結果通過ajax回來..類似的東西? :

$j.ajax({ 
    url: readurl, 
    type: "GET", 
    data: 'sku=' + thisSku, 
    dataType: "json", 
    success: function (data){ 
     // ? now what 
    }  
}); 

有人可以幫我理解我現在可以採取json數據來選擇適當的選擇嗎?如果note_id與輸入[name]屬性匹配,如何檢查具有適當值的按鈕,我將如何創建運行檢查的循環? json甚至是處理這個問題的最好方法嗎?我應該使用.getJSON()嗎?

+1

+1向我們展示了學習的意圖。 – 2012-04-18 14:59:06

回答

6

裏面的成功回調,你可以簡單地在data迭代這應該是[{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}]

DEMO

$.each (data, function (i, obj) { 
    $(':radio[name=' + obj.note_id + '][value=' + obj.value + ']').prop('checked', true); 
}); 
+0

這很好用!謝謝! – Zac 2012-04-18 15:08:28

2
var data = {"nodes": [{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}] } 

$('input:radio').attr('checked','') 
$.each(data.nodes,function(a,b){ 
    $("input[name="+b.note_id+"][value="+b.value+"]:radio").attr('checked','checked') 

}) 

也許類似的東西會爲你工作...

2

JSON對象上創建一個$。每()循環,然後比較名稱值note_id並添加屬性

var notas = [{"note_id":"1","value":"no"},{"note_id":"4","value":"yes"},{"note_id":"5","value":"yes"}]; 


$.each(notas,function(i, v){ 
    $('input[type=radio][name=' + this.note_id + ']').prop('checked','true'); 

}); 
​ 

http://jsfiddle.net/chepe263/wLDHk/

0

嘗試是這樣的:

$j.ajax({ 
    url: readurl, 
    type: "GET", 
    data: 'sku=' + thisSku, 
    dataType: "json", 
    success: function (data){ 
     $.each(data, function(i, item) { 
      alert("note_id: " + item.note_id + ", value: " + item.value); 
     }); 
    }  
}); 

你腦水腫,以取代去你的代碼的警報。

Greatings。