-1

I have a form and I want to get which checkbox is selected in plain JS and get its value returned. I get it with radio buttons but not with checkbox and just cant figure out how should it be called if I call it the same as with radio buttons it returns empty string code below.

Example with radio buttons:

   /*html*/
   <input type="radio" name="q5" value="a" id="q5a">a. test1<br>
   <input type="radio" name="q5" value="b" id="q5b">b. test2<br>

   /*js, gets the value which is selected either a or b as per html*/
   var q5 = document.forms["quizForm"]["q5"].value;

Now I try this with checkboxes:

   /*html*/
   <input type="checkbox" name="q6" value="c" id="q6c">c. test1<br>
   <input type="checkbox" name="q6" value="d" id="q6d">d. test2<br>

   /*js returns an empty string "" when either checked or both*/
   var q6 = document.forms["quizForm"]["q6"].value;
Zygimantas
  • 553
  • 8
  • 22

2 Answers2

1

Checkbox behavior is different from the radio.

var checkedValue = null; 
var inputElements = document.getElementsByName('q6');
for(var i=0; inputElements[i]; ++i){
  if(inputElements[i].checked){
    checkedValue = inputElements[i].value;
    break;
  }
}

got from

karran
  • 304
  • 1
  • 6
1

It should actually be:

document.forms["quizForm"]["q5"].checked

And your form should have a name or an id equal to "quizForm" e.g. <form name="quizForm" ...> or <form id="quizForm" ...>

Ikbel
  • 7,721
  • 3
  • 34
  • 45