2017-09-29 44 views
0

我真的需要你的幫助,我似乎無法找到類似的解決方案,那裏將提供我所需要的支持,以便在此嘗試完成。如何檢查基於數組值的複選框

如何根據數組中的值以編程方式檢查以下複選框。

var arr = ['recurr_date2','recurr_date4'] 

我想檢查它的值是recurr_date2和recurr_date4

下面是HTML標記的複選框:

<input name="recurr_target" value="recurr_date2" type="checkbox"> 
<input name="recurr_target" value="recurr_date3" type="checkbox"> 
<input name="recurr_target" value="recurr_date4" type="checkbox"> 

我很好的前面回答也使用jQuery

+0

相關:https://stackoverflow.com/questions/17537579/check-checkboxes-based-on-values-in-an-array –

回答

-2

使用filter檢查輸入值是否在數組中。

var arr = ['recurr_date2', 'recurr_date4']; 
 

 
$("input[name='recurr_target']").filter(function() { 
 
    return arr.indexOf(this.value) != -1; 
 
}).prop("checked", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<input name="recurr_target" value="recurr_date2" type="checkbox" /> 
 
<input name="recurr_target" value="recurr_date3" type="checkbox" /> 
 
<input name="recurr_target" value="recurr_date4" type="checkbox" />

+0

'返回$(本);'很奇怪。爲什麼要經歷創建一個新的jquery對象的麻煩,只是爲了將所述對象轉換爲布爾值 –

+0

filter期望返回一個布爾值。如果你返回其他東西,它將被轉換爲布爾值。如果沒有if語句,你很可能剛剛返回了條件語句。這是多餘的。 '如果(真)返回true;' - >'返回true' –

-1

試試這個。

var arr = ['recurr_date2','recurr_date4'] 
arr.forEach(function(ar){ 
    if(!$('input[value='+ar+']').prop('checked'))//see if its unchecked 
    $('input[value='+ar+']').click() 
}) 
-1
var arr = ['recurr_date2','recurr_date4'] 
for(let name of arr) { 
    document.querySelector(`[value="${name}"]`).setAttribute('checked', '') 
} 

下面是做什麼:

  1. 遍歷複選框的列表中剔掉
  2. 獲取的DOM元素吧
  3. 添加checked屬性
相關問題