Click here to Skip to main content
15,919,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, guys I have three radio buttons. I want to assign value of them to a variable but the value stays the same whichever button is clicked.

What I have tried:

HTML

HTML
<input type="radio" name="age" onclick="checkAge(this)" value="child">less tan 18<br>
<input type="radio" name="age" onclick="checkAge(this)" value="adult">over 18<br>
<input type="radio" name="age" onclick="checkAge(this)" value="senior">over 65<br>


JavaScript
function checkAge(radio){
   var age = "";
  if(radio.value="child"){
    age = "child";
  }
  else if (radio.value="adult") {
    age = "adult";
  }
  else {
    age = "senior";
  }
  console.log(age);

}


The value of the variable 'age' is not changing, why?
Posted
Updated 15-Mar-17 1:35am

You have missed "==". Please open the below link (Tryit Editor v3.3[^]) and copy the code to verify.

<!DOCTYPE html>
<html>
<body>
<script>
function checkAge(radio){
alert(radio.value);
   var age = "";
  if(radio.value=="child"){
    age = "child";
  }
  else if (radio.value=="adult") {
    age = "adult";
  }
  else {
    age = "senior";
  }
  alert(age);

}
</script>
<form action="">
  <input type="radio" name="gender" onclick="checkAge(this)" value="child"> child<br>
  <input type="radio" name="gender" onclick="checkAge(this)" value="adult"> adult<br>
  <input type="radio" name="gender" onclick="checkAge(this)" value="senior"> senior
</form>

<p> * The selected value will be shown in the alert box upon select. </p>
</body>
</html>


Thank you.
 
Share this answer
 
use == instead of =

if (radio.value == "child") {


but this will do the job
function checkAge(radio) {
           console.log(radio.value);
       }
 
Share this answer
 
v2
Comments
Reatellino 15-Mar-17 7:28am    
OMG, How could I miss it! hahaha. Thank You:)
Karthik_Mahalingam 15-Mar-17 7:29am    
welcome :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900