2017-12-18 109 views
1

我在html中有4個複選框。我想如果任何複選框被選中,它的值被存儲在數組中。我創建了一個功能,但它顯示了空數組使用jquery動態構建數組

var arry = []; 
 

 
function CheckBox(check) { 
 
    debugger 
 

 
    for (i = 0; i < check.length; i++) { 
 
    if (check[i].checked == true) { 
 
     arry.push(check[i].value); 
 
     alert(arry); 
 
    } 
 
    } 
 

 
} 
 

 
$(document).ready(function() { 
 

 
    $("#btn").click(function() { 
 
    debugger; 
 
    alert(arry); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <input type="checkbox" id="chk1" value="1" class="chk" onclick="CheckBox(this)" />1 
 
    <input type="checkbox" id="chk2" value="2" class="chk" onclick="CheckBox(this)" />2 
 
    <input type="checkbox" id="chk3" value="3" class="chk" onclick="CheckBox(this)" />3 
 
    <input type="checkbox" id="chk4" value="4" class="chk" onclick="CheckBox(this)" />4 
 
    <input type="button" id="btn" value="alert" /> 
 
</div>

+0

我固定的代碼段陣列。請多加小心 – mplungjan

回答

2
  1. 您可以使用.each()循環複選框
  2. 使用.is(":checked")檢查檢查狀態

$(document).ready(function() { 
 

 
    $("#btn").click(function() { 
 
    var arry = []; 
 
    $.each($(".chk"), function() { 
 
     if ($(this).is(":checked")) { 
 
     arry.push($(this).val()); 
 
     } 
 

 
    }) 
 
    console.log(arry) 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <input type="checkbox" id="chk1" value="1" class="chk" />1 
 
    <input type="checkbox" id="chk2" value="2" class="chk" />2 
 
    <input type="checkbox" id="chk3" value="3" class="chk" />3 
 
    <input type="checkbox" id="chk4" value="4" class="chk" />4 
 
    <input type="button" id="btn" value="alert" /> 
 
</div>

1

幾個問題。最糟糕的是沒有得到函數中的複選框。

你通過一個盒子,而不是一個盒子

var arry = []; 
 
function CheckBox(check) { 
 
    arry = []; 
 
    $("."+check.className).each(function() { // get the other checks 
 
    if (this.checked) { // or jQuery: $(this).is(":checked"); 
 
     arry.push(this.value); // or jQuery $(this).val() 
 
     alert(arry); 
 
    } 
 
    }) 
 
} 
 

 
$(document).ready(function() { 
 

 
    $("#btn").click(function() { 
 
    alert(arry); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <input type="checkbox" id="chk1" value="1" class="chk" onclick="CheckBox(this)" />1 
 
    <input type="checkbox" id="chk2" value="2" class="chk" onclick="CheckBox(this)" />2 
 
    <input type="checkbox" id="chk3" value="3" class="chk" onclick="CheckBox(this)" />3 
 
    <input type="checkbox" id="chk4" value="4" class="chk" onclick="CheckBox(this)" />4 
 
    <input type="button" id="btn" value="alert" /> 
 
</div>

0

添加下面的變化,你的JavaScript/jQuery代碼

$("#btn").click(function() { 
    var arry = []; 
    $.each($(".chk"), function() { 
     if ($(this).is(":checked")) { 
     arry.push($(this).val()); 
     } 

    }) 
    alert(arry) 
    }); 
});