jquery multiple checkboxes array

前端 未结 6 1356
孤独总比滥情好
孤独总比滥情好 2020-12-04 19:45




        
相关标签:
6条回答
  • 2020-12-04 20:01
    var checked = []
    $("input[name='options[]']:checked").each(function ()
    {
        checked.push(parseInt($(this).val()));
    });
    
    0 讨论(0)
  • 2020-12-04 20:01

    If you have a class for each of your input box, then you can do it as

            var checked = []
            $('input.Booking').each(function ()
            {
                checked.push($(this).val());
            });
    
    0 讨论(0)
  • 2020-12-04 20:14

    This way will let you add or remove values when you check or uncheck any checkbox named as options[]:

    var checkedValues = [];
    $("input[name='options[]']").change(function() {
        const intValue = parseInt($(this).val());
        if ($(this).is(':checked')) {
            checkedValues.push(value);
        } else {
            const index = checkedValues.indexOf(value);
            if (index > -1) {
               checkedValues.splice(index, 1);
            }
        }
     });
    
    0 讨论(0)
  • 2020-12-04 20:19
    var checkedString = $('input:checkbox:checked.name').map(function() { return this.value; }).get().join();
    
    0 讨论(0)
  • 2020-12-04 20:24

    A global function that can be reused:

    function getCheckedGroupBoxes(groupName) {
    
        var checkedAry= [];
        $.each($("input[name='" + groupName + "']:checked"), function () {
            checkedAry.push($(this).attr("id"));
        });
    
         return checkedAry;
    
    }
    

    where the groupName is the name of the group of the checkboxes, in you example :'options[]'

    0 讨论(0)
  • 2020-12-04 20:27

    You can use $.map() (or even the .map() function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number

    var arr = $.map($('input:checkbox:checked'), function(e,i) {
        return +e.value;
    });
    
    console.log(arr);
    

    Here's an example

    0 讨论(0)
提交回复
热议问题