简体   繁体   English

复选框值选中和未选中的数组

[英]array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array. 我有此功能,当我选中一个或多个复选框时,该函数将加载已选中复选框的值...但是,当我取消选中一个或多个复选框时,该函数将显示一个空数组。

this is the function: 这是功能:

$(document).ready(function () {
   $('input[type="checkbox"]').change(function () {
         var mycheck = new Array();
         if ($(this).is(':checked')) {
            $("#line-checkbox-1:checked").each(function () {
                mycheck.push($(this).val());//aggiungo value del checked
            });
             alert(mycheck)


        } else {
            var itemtoRemove = $(this);
            mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked

            alert(mycheck);


        }

    });

This is HTML of the checkbox: 这是复选框的HTML:

    <div class="col-lg-3">
 <input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">

 </div>

Try This Simple Script, this works for you: 试试这个简单的脚本,它为您工作:

HTML 的HTML

<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />

JQUERY JQUERY

$(document).ready(function () 
{
   $('input[type="checkbox"]').change(function () 
   {
        var arr = $.map($('input:checkbox:checked'), function(e,i) {
            return +e.value;
        });
        alert(arr);
    });
});

Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. 可能是因为您使用id来引用复选框,并且由于每次用户更改复选框都从头开始创建阵列。 you should recheck the list everytime a checkbox is changed. 您应该在每次复选框更改后重新检查列表。 That means you dont need that if.( if($(this).is(":checked") ) 这意味着您不需要if。(if($(this).is(“:checked”))

$('.checkboxes input[type="checkbox"]').change(function () {
    var mycheck = new Array();

    $(".checkboxes input[type='checkbox']:checked").each(function () {
        if ($(this).is(':checked')) {
            mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
        }
    });
    alert(mycheck);
});

here is a fiddle if i understand correctly what you are trying to do 这是一个小提琴,如果我正确理解您要做什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM