How ToJavaScriptColor PickerMake Web StoriesQuiz GeneratorFAQ Schema GeneratorTable Maker3schools TranslateImage Compressor
Apu
Apu 12/09/2022

How to store selected checkbox value in array in JavaScript

In this article, you will learn how to store selected checkbox value in array using JavaScript or how to get multiple checkbox value in JavaScript .

Store all selected checkbox value in array using for loop.

In the first example, I will show you the example by using javascript for loop.

Example using for loop
function myFunc() {
 let arr = [];
 let checkboxes = document.querySelectorAll("input[type='checkbox']:checked");
 for (let i = 0 ; i < checkboxes.length; i++) {
  arr.push(checkboxes[i].value)
 }
}
Try it Yourself »
  1. When the Store Value button is clicked, the myFunc() function gets called.
  2. Inside this function, create a new blank array (let arr = []). Then, store the selected checkbox into a variable using querySelectorAll() method.
  3. The querySelector() method returns the first element that matches the specified selectors. But querySelectorAll() method returns all the elements that matches the specified selectors as a NodeList representing a list of the selected elements .
  4. Then create a for loop inside the myFunc() function. When the loop is executed , the selected value is inserted into the blank array using the push() method.
  5. Finally, convert the array into a string using toString() method and display the value using javascript alert box.

Store selected checkbox values in array using forEach() method.

Use the forEach() method to store all selected checkbox values in an array. The example is given below.

<script>
function myFunc() {
 let arr = [];
 let checkboxes = document.querySelectorAll("input[type='checkbox']:checked");

checkboxes.forEach((item)=>{
   arr.push(item.value)
}) 

console.log(arr);
}
</script>
Share
Save

How to store selected checkbox value in array in JavaScript

1
In this article, you will learn how to store selected checkbox value in array using JavaS…
asked
1 answers

1 Answers

Related Posts (More answers below)
  1. Select checkboxes and click on the submit button and check out the console.
    https://www.3schools.in/p/code-editor.html?q=CjxpbnB1dCB0eXBlPSJjaGVja2JveCIgdmFsdWU9InZhbHVlIDEiIC8+CjxpbnB1dCB0eXBlPSJjaGVja2JveCIgdmFsdWU9InZhbHVlIDIiIC8+CjxpbnB1dCB0eXBlPSJjaGVja2JveCIgdmFsdWU9InZhbHVlIDMiIC8+CjxpbnB1dCB0eXBlPSJjaGVja2JveCIgdmFsdWU9InZhbHVlIDQiIC8+CjxpbnB1dCB0eXBlPSJjaGVja2JveCIgdmFsdWU9InZhbHVlIDUiIC8+CjxpbnB1dCB0eXBlPSJjaGVja2JveCIgdmFsdWU9InZhbHVlIDYiIC8+Cgo8YnV0dG9uIG9uY2xpY2s9Im15RnVuYygpIj4gU3VibWl0PC9idXR0b24+CjxzY3JpcHQ+CmZ1bmN0aW9uIG15RnVuYygpIHsKIGxldCBhcnIgPSBbXTsKIGxldCBjaGVja2JveGVzID0gZG9jdW1lbnQucXVlcnlTZWxlY3RvckFsbCgiaW5wdXRbdHlwZT0nY2hlY2tib3gnXTpjaGVja2VkIik7CgpjaGVja2JveGVzLmZvckVhY2goKGl0ZW0pPT57CiAgIGFyci5wdXNoKGl0ZW0udmFsdWUpCn0pIAoKY29uc29sZS5sb2coYXJyKTsKfQo8L3NjcmlwdD4=
    Reply Delete
    Share
    Save
Write Your Answer
back