user9855996
user9855996

Reputation:

How to access the value of a radio button

I am trying to access the value of a radio button using HTML and Javascript to make a simple quiz but it does not seem to be working. Here is my code:

function check() {
var a = document.getElementById("test").value
if (a === "one") {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
  <input type="radio" name="one" id="test" value="one">1<br>
  <input type="radio" name="one" id="test" value="two">2<br>
  <input type="radio" name="one" id="test" value="three">3<br>
  <button onclick="check()">Check</button>
</form>

It always says "Correct!" even when it is not. Does anyone know how to fix this?

Upvotes: 0

Views: 72

Answers (3)

CodeF0x
CodeF0x

Reputation: 2681

Some points you are missing:

  • An id must be unique on the whole page
  • To check if a radio button is checked, use its checked attribute

function check() {
  var two = document.getElementById("two");
  if (two.checked) {
    alert("Correct!")
  } else {
    alert("Wrong!")
  }
}
<h1>
  <center>Simple Quiz</center>
</h1>
<br> 1) What is 1 + 1?
<br>
<form>
  <input type="radio" name="one" id="one" value="one">1<br>
  <input type="radio" name="one" id="two" value="two">2<br>
  <input type="radio" name="one" id="three" value="three">3<br>
  <button onclick="check()">Check</button>
</form>

Upvotes: 1

juancarlos
juancarlos

Reputation: 631

you should not define more than one element with the same id that's a bad practice, you could improve your code function check() { for (elemnt of document.getElementByClassName('test') ) { if (element.checked ) alert('correct'); else alert ("incrrect");}} Them in the html you can do this <input type="radio" class="test" value="1">

<input type="radio" class="test" value="2"> <input type="radio" class="test" value="3">

Upvotes: 0

Milos Lazarevic
Milos Lazarevic

Reputation: 76

First, you cannot have the same id on multiple elements. Make to give your elements a unique id and if you need to give them all the same style you could use class instead.

Instead of checking the value of the radio button, you should check whether the radio button is checked.

Take a look at the example below.

function check() {
  if (document.getElementById('test2').checked) {
    alert('correct');
  } else {
    alert('wrong');
  }
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
</head>
<body>
  <h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
  <input type="radio" name="one" id="test1" value="one">1<br>
  <input type="radio" name="one" id="test2" value="two">2<br>
  <input type="radio" name="one" id="test3" value="three">3<br>
  <button onclick="check()">Check</button>
</form>
</body>
</html>

Upvotes: 0

Related Questions