user557108
user557108

Reputation: 1215

jquery multiple checkboxes array

<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" />

How I can make an array with values of checkboxes that are checked?

NOTE: (IMPORTANT) I need an array like [1, 2, 3, 4, 5] and not like ["1", "2", "3", "4", "5"] .
NOTE: There are around 50 checkboxes.

Can someone help me? Please!

Thank you!

Upvotes: 46

Views: 118451

Answers (7)

Raja
Raja

Reputation: 461

Pure javascript answer

const checked = Array.from(
    document.querySelectorAll(`input[name=myCheckboxGroup]:checked`)).map(node=>node.value);

Upvotes: 0

Pedro Trujillo
Pedro Trujillo

Reputation: 1691

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);
        }
    }
 });

Upvotes: 3

Hasan Shouman
Hasan Shouman

Reputation: 2362

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[]'

Upvotes: 1

Muhammad Amjad
Muhammad Amjad

Reputation: 326

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());
        });

Upvotes: 2

user2503922
user2503922

Reputation: 29

var checkedString = $('input:checkbox:checked.name').map(function() { return this.value; }).get().join();

Upvotes: 3

Russ Cam
Russ Cam

Reputation: 125488

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

Upvotes: 58

Dormouse
Dormouse

Reputation: 5198

var checked = []
$("input[name='options[]']:checked").each(function ()
{
    checked.push(parseInt($(this).val()));
});

Upvotes: 87

Related Questions