2010-01-13 113 views
2

的陣列這裏是我的複選框組如何獲取複選框

<input type="checkbox" name="checkGroup" id="all" value="0" >All 
<input type="checkbox" name="checkGroup" id="one" value="1">One 
<input type="checkbox" name="checkGroup" id="two" value="2">Two 
<input type="checkbox" name="checkGroup" id="three" value="3">three 

如何通過名爲「checkGroup」獲得複選框的數組,然後在價值基礎設置檢查/取消選中。

例如 在編輯模式下,我從數據庫 得到字符串012,那麼我需要設置檢查爲全部,一個和兩個。

請幫助謝謝

回答

1

如果你去了這個方法,返回不受任何字符分隔的數字的字符串(如「012」),你只能處理沒有問題多達10個元素( 0-9):

function checkItems(str) { 
    var checkboxes = $("input:checkbox[name='checkGroup']"); 
    checkboxes.attr('checked', false); // uncheck all boxes first 
    checkboxes.each(function() { 
    if (str.indexOf(this.value) >=0) { 
     this.checked = true; 
    } 
    }); 
} 

checkItems('012'); // checks all, one, and two 

檢查爲例here

+0

什麼與值12不是在0,1或2,但似乎是因爲012類似於0 12? – Sampson 2010-01-13 04:56:09

+0

用''12'它會檢查「一個」和「兩個」框(我認爲這是OP所期望的行爲) – CMS 2010-01-13 05:01:01

+0

ya其工作thanksJonathan – Vicky 2010-01-13 05:01:05

1
// Help us with finding values in arrays 
Array.prototype.has=function(v){ 
    for (i=0; i<this.length; i++) { 
    if (this[i]==v) return true; 
    } 
    return false; 
} 

// Define our values 
var myVals = [0,1,2]; 

// Check/Uncheck Accordingly 
$(":checkbox[name='checkGroup']").each(function(){ 
    if (myVals.has($(this).val())) { 
    $(this).attr("checked","checked"); 
    } else { 
    $(this).removeAttr("checked"); 
    } 
});