123
123

Reputation: 278

How get the value of multiple checkboxes in javascript

I used checkbox in two items now I can get the value of the second group of checkbox. The first group of checkbox I use:

<input name="option" type="checkbox" value="1" id="option1">option 1
<input name="option" type="checkbox" value="2" id="option2">option 2

Then

<input name="choice" type="checkbox" value="1" id="choice1">choice 1
<input name="choice" type="checkbox" value="2" id="choice2">choice 2

How can i get the value of selected checkboxes, in each group it is only allowed to select 1 checkbox.

I just need the javascript function

Upvotes: 0

Views: 12344

Answers (6)

Raja
Raja

Reputation: 461

No jQuery Pure Javascript

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

Upvotes: 0

Pedro Fillastre
Pedro Fillastre

Reputation: 922

With Jquery

var checked; 
$("input").each(function () {
   if ($(this).is(':checked'))
     checked[ $(this).attr("name")] = $(this).attr("value")
})
//checked is an array/object with all your checked checkboxs

Upvotes: 1

user1342883
user1342883

Reputation:

You can use this following codes to get the value of the checkbox if you are using multiple checkboxes.

$('input[name=option]:checked').val();

Upvotes: 3

Shaikh Farooque
Shaikh Farooque

Reputation: 2640

Katherine if you want to select a single item from both the groups then you should go for the radio other wise you can not restrict to select only one check box and unnecessary you have to write a bulk of worth less code for that.

Also you have to mention the array of check boxes. the syntax you have taken is wrong the correct one is

<input name="option[]" type="checkbox" value="1" id="option1">option 1
<input name="option[]" type="checkbox" value="2" id="option2">option 2

and for radios

<input name="option" type="radio" value="1" id="option1">option 1
<input name="option" type="radio" value="2" id="option2">option 2

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

You want a radio button, (where only one option can be selected at a time)

<input name="option" type="radio" value="1" id="option1">option 1
<input name="option" type="radio" value="2" id="option2">option 2

Checkboxes can be grouped into arrays by appending [] to the end of their names:

<input name="option[]" type="checkbox" value="1" id="option1">option 1
<input name="option[]" type="checkbox" value="2" id="option2">option 2

This will not get the effect you want, it will instead group the checkboxes so that all input from them will result in one array. it is still possible to select multiple checkboxes with this method.

Upvotes: 5

Rahul Raj
Rahul Raj

Reputation: 11

And retrieve the value of radio button as document.formName.radioboxName.value;

Since you are giving same name for the radio buttons, only one value can be selected.

Upvotes: 1

Related Questions