Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare id in Javascript

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>
like image 498
Hanis Zahirah Avatar asked Mar 19 '26 10:03

Hanis Zahirah


1 Answers

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.";
like image 182
Codeheir Avatar answered Mar 22 '26 00:03

Codeheir