How to verify a Radio Box selection using a JavaScript array (I think?)


#1

I am creating a quiz and I need help. I want an easy way to verify that the correct answer was selected from a set of Radio Buttons using an array approach (I think…?).

Please Note: This code/project is evolving and I am only in the first stages of development and I am still learning best practices. Suggestions for improvement are welcome.

My goal: JavaScript function to verify whether or not any option has been selected.
Next Step: Determine if the correct answer is selected.

My question:
When I run the function valGender() below, it only returns the value of true if the first option (male) is selected. Therefore when female or Other is selected, the function returns false.

What have I done wrong?

Below is the form code:

<html>
<head></head>
<body>
 <form>
<label>Male</label><input type="radio" name="gender" id = "g_male" value="male">
<label>Female</label><input type="radio" name="gender" id = "g_female" value="female">
<label>Other</label><input type="radio" name="gender" id = "g_other" value="other">
<button type="button" onclick="valGender()">Submit</button>
</form>
<p id="sel"></p>
<p id="ans"></p>
</body>
</html>

Below is the JavaScript Function

function valGender() {
    var genarr = document.getElementsByName("gender");
	var valgen =false;
	
    for (var i=0; i < genarr.length; i++){
     if(genarr[i].checked){		
	 valgen=true;
document.getElementById("sel").innerHTML = "Option " + i + " is selected";

		 	 }
				
document.getElementById("ans").innerHTML = "Valgen value is: " + valgen;
}
}


#2

Hi there MWms,

does this help…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<!--<link rel="stylesheet" href="screen.css" media="screen">-->

<style media="screen">
body {
    background-color: #f9f9f9;
    font: 100% / 162% verdana, arial, helvetica, sans-serif;
 }

</style>

</head>
<body> 

 <form action="#">
  <label>Male</label>
   <input type="radio" name="gender" id="g_male" value="male">
  <label>Female</label>
   <input type="radio" name="gender" id="g_female" value="female">
  <label>Other</label>
   <input type="radio" name="gender" id="g_other" value="other">
  <button type="button" id="but">Submit</button>
 </form>

<p id="sel"></p>
<p id="ans"></p>

<script>
 (function( d ) {
   'use strict';
   d.getElementById( 'but' ).addEventListener( 'click', 
   function()  {
     var i, valgen, genarr = d.getElementsByName( 'gender' );
      for ( i = 0; i < genarr.length; i ++ ){
         if ( genarr[i].checked === true ){		
              valgen = true;
              d.getElementById( 'sel' ).textContent = 'Option ' +  i  + ' is selected';
            }
	      else {
              valgen = false;
            }			
              d.getElementById( 'ans' ).textContent = 'Valgen value is: ' + valgen;
          }
       }, false );
 }(document));
</script>

</body>
</html>

coothead


#3

Thank you for the revised code. Yes it really does help. It makes the solution more robust and I can understand how this approach would be much more effective than my original code.

However, I am still a bit confused about something.

Why does the following code not work?

>  for (var i=0; i < genarr.length; i++){
>      if(genarr[i].checked){	

While your solution DOES work?

> for ( i = 0; i < genarr.length; i ++ ){
>          if ( genarr[i].checked === true ){		

In other words, do I need to always set genarr[i].checked === true?

For some reason when I ran my code the for loop and if conditions didn’t recognize option 2 (female) and option 3 (other). Will this “glitch” occur in your code as well?


#4

Yes you do. :winky:

That is the state which your if condition is seeking. :biggrin:

coothead


#5

Are you sure? I was thinking it was

	      else {
              valgen = false;
            }	

that was responsible for the difference.


#6

how so?


#7

If you temporarily take those lines out does the code still work as expected?


#8

From your original post, the genarr[i].checked logic works fine.
The if is just checking for true and false conditions of the radio buttons.
But NOTE, the condition will not be guaranteed to be either if it is NOT checked.

You will always get a valgen as true if you check a radio button.
You can get the actual value of the radio button if you modify to this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> HTML5 page </title>
</head>
<body>
<form>
<label for='g_male'>Male</label><input type="radio" name="gender" id = "g_male" value="male">
<label for='g_female'>Female</label><input type="radio" name="gender" id = "g_female" value="female">
<label for='g_other'>Other</label><input type="radio" name="gender" id = "g_other" value="other">
<button type="button" onclick="valGender()">Submit</button>
</form>
<p id="sel"></p>
<p id="ans"></p>

<script>
function valGender() {
  var genarr = document.getElementsByName("gender"),
      valgen = '';  // false;
  for (var i=0; i < genarr.length; i++){
    if(genarr[i].checked){		
      valgen = genarr[i].value;  // true;
      document.getElementById("sel").innerHTML = "Option " + i + " is selected";
    }
    document.getElementById("ans").innerHTML = "Valgen value is: " + valgen;
  }
}
</script>
</body>
</html>