I tried to compare a simple code where if user click on the button, then the output will display appropriate answer but I can't seem to find any correct way to do it.
<!DOCTYPE html>
<html>
<body>
<p>Gender</p>
<label><input type="radio" name="gender" id="male" value="Male">Male</label>
<label><input type="radio" name="gender" id="male" value="Female">Female</label>
<br>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo">
<script>
function myFunction() {
var x = document.getElementById("demo").value;
var m = document.getElementById("male").value;
var f = document.getElementById("female").value;
if(x === m)
x.innerHTML = "You are male.";
else if(x === f)
x.innerHTML = "You are female.";
}
</script>
</body>
</html>
You want something like the following:
<html>
<body>
<p>Gender</p>
<label><input type="radio" name="gender" id="male" value="Male">Male</label>
<label><input type="radio" name="gender" id="female" value="Female">Female</label>
<br>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo">
<script>
function myFunction() {
var x = document.getElementById("demo");
var m = document.getElementById("male").checked;
var f = document.getElementById("female").checked;
if (m)
x.innerHTML = "You are male.";
else if (f)
x.innerHTML = "You are female.";
}
</script>
</body>
</html>
First of all you had the id for both the inputs to male, you want the female input to be female:
<label><input type="radio" name="gender" id="female" value="Female">Female</label>
Secondly you want to get whether the radio button is checked, not it's value:
var m = document.getElementById("male").value; // returns Male in your case
var m = document.getElementById("male").checked; // returns true or false depending on whether it's been checked
Then the logic needs a bit of an alteration:
if (m) // they selected male
x.innerHTML = "You are male.";
else if (f) // they selected female
x.innerHTML = "You are female.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With