获取有关将组复选框更改为数组的值

时间:2018-05-28 17:14:53

标签: javascript jquery

我正在制作这个演示。
为什么我无法在选中和取消选中复选框时获取复选框值?

// find elements
$('input:checkbox[name=product]').on('change', function() {
    var val = '';
    $('input:checkbox[name=product]:checked').each(function() {
        val += $(this).val();
    });
    switch (val) {
        case 'all':
             console.log(val);
            break;
        case 'women':
             console.log(val);
            break;
        case 'men':
             console.log(val);
            break;
	  case 'men':
             console.log(val);
            break;
       }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="product" value="all" checked />All Genders <br />
<input type="checkbox" name="product" value="women" />Women <br />
<input type="checkbox" name="product" value="men" />Men<br />
<input type="checkbox" name="product" value="bi" />Bi<br />

2 个答案:

答案 0 :(得分:1)

switch条件应该进入每个循环。

&#13;
&#13;
// find elements
$('input:checkbox[name=product]').on('change', function() {
    var valueArray = [];
    $('input:checkbox[name=product]:checked').each(function() {
        var val = $(this).val();
        valueArray.push(val);

        switch (val) {
            case 'all':
                console.log(val);
                break;
            case 'women':
                console.log(val);
                break;
            case 'men':
                console.log(val);
                break;
            case 'men':
                console.log(val);
                break;
        }
    });
    console.log("final checked box array");
    console.log(valueArray);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="product" value="all" checked />All Genders <br />
<input type="checkbox" name="product" value="women" />Women <br />
<input type="checkbox" name="product" value="men" />Men<br />
<input type="checkbox" name="product" value="bi" />Bi<br />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您只需要控制日志记录已检查的值,不需要任何开关案例。

&#13;
&#13;
// find elements
$('input:checkbox[name=product]').on('change', function() {
    var val = '';

    $('input:checkbox[name=product]:checked').each(function() {
        val = $(this).val();
        console.log(val)
    });
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="product" value="all" checked />All Genders <br />
<input type="checkbox" name="product" value="women" />Women <br />
<input type="checkbox" name="product" value="men" />Men<br />
<input type="checkbox" name="product" value="bi" />Bi<br />
&#13;
&#13;
&#13;