簡體   English   中英

使用jQuery選擇組中的多個復選框

[英]Selecting multiple check boxes in a group using jQuery

我必須選擇一個組中的許多復選框,如果我必須由用戶提供一個像[“ 1”,“ 3”,“ 8”]這樣的列表,並且我必須選擇10個復選框,其值屬性設置為0到9復選框,值為1,3和8。如何完成? 請回復 !!

var arr = ['1','3','8'];
/* find all the checkbox input elements.
   set the 'checked' property */
$('input[type=checkbox]').prop('checked', function(){
    // return  true if the value is in the array, false if not
    return $.inArray(this.value, arr) > -1;
});

JS小提琴演示

或者,使用filter()

var arr = ['1','3','8'];

$('input[type=checkbox]').filter(function(){
    return $.inArray(this.value, arr) > -1;
}).prop('checked',true);

JS小提琴演示

但是,值得的是,在設置屬性之前,首先取消選中所有已選中的復選框:

var arr = ['1','3','8'];

$('input[type=checkbox]').prop('checked',false).filter(function(){
    return $.inArray(this.value, arr) > -1;
}).prop('checked',true);

JS小提琴演示

最后,由於inputvalue始終是字符串,而JavaScript中的數字不必加引號,因此可以在數組中使用未加引號的數字(以防健忘,如果沒有其他原因):

var arr = ['1',3,'8'];

$('input[type=checkbox]').prop('checked',false).filter(function(){
    return $.inArray(this.value, arr.toString()) > -1;
}).prop('checked',true);

JS小提琴演示

參考文獻:

例如,對於值8:

<input type="checkbox" class="chk" name="myGroup[]" value="7" />
<input type="checkbox" class="chk" name="myGroup[]" value="8" />

<script>
  $(".chk[value='8']").prop("checked", true);
</script>

這是一種實現方法-為您的復選框提供一個通用類,即“ myCheckbox”。

使用jQuery遍歷所有帶有“ myCheckbox”類的復選框,並將其值與用戶提供的列表進行比較。 如果有匹配項,請選中該復選框。

偽jQuery代碼:

$('.myCheckbox').each(function() {
  // you would search the array here
  if ($(this).value == "1") {
    $(this).check();
  }
});

你可以試試這個-

var arr =  ["1","3","8"];
$(':checkbox').each(function(){
  if($.inArray(this.value,arr) > -1){
   $(this).prop('checked',true);
  }
}) 

這應該可以解決您的問題:

var setArr = ["1","3","8"];

$('.checkbox').each(function(i, j){
if(jQuery.inArray($(j).val(), setArr)!= -1){

$(j).attr('checked', 'checked');
}

});

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM