Radio buttons function not working

function fn1()
{
var r1 = document.getElementById("rl");
var r2 = document.getElementById("r2");

if(r1.checked==true)
alert("U are a human and panda");
 else
  alert("U are Nothing");
 }

Can you please describe the problem you are having?

when I am running it, and I check the radio button the alert function message does not appear

Can you share all of your code?

<html>
<div style="position: absolute; top: 370px; left:750px; height:150px;width:250px; background-color:red;">
  <input type="textbox" id="textbox">
  <button id="button">Send</button>
  <ul id="messages"></ul>
</div>
<div style="position: absolute; top: 550px; left:750px; height:150px;width:250px; background-color:red;">
  <input type="radio" id="r1" >I am a panda</input><br>
  <input type="radio" id="r2" >I am a human</input><br>
  <button type="button" onclick="fn1()" id="bt1" > Submit </button>
</div>
</html>
<script>

function fn1()
{
var r1 = document.getElementById("rl");
var r2 = document.getElementById("r2");

if(r1.checked==true)
alert("U are a human and panda");
 else
  alert("U are Nothing");
 }
</script>

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

<html>
<div style="position: absolute; top: 370px; left:750px; height:150px;width:250px; background-color:red;">
  <input type="textbox" id="textbox">
  <button id="button">Send</button>
  <ul id="messages"></ul>
</div>
<div style="position: absolute; top: 550px; left:750px; height:150px;width:250px; background-color:red;">
  <input type="radio" id="r1" >I am a panda</input><br>
  <input type="radio" id="r2" >I am a human</input><br>
  <button type="button" onclick="fn1()" id="bt1" > Submit </button>
</div>
</html>
<script>

function fn1()
{
var r1 = document.getElementById("rl");
var r2 = document.getElementById("r2");

if(r1.checked==true)
alert("U are a human and panda");
 else
  alert("U are Nothing");
 }
</script>

It looks like your function is never being called.

No it called fn1() and in the Html button tag I mentioned that onclick=“fn1()”
if I misunderstand u right please explain with more details

Ah, now I see.

If we dump this into codepen, I am seeing this error when I click the button:

TypeError: r1 is null

so the question is why.


I think you have a typo in the id for that element.

1 Like

there is an error in your function

var r1 = document.getElementById("rl"); // should be r1 not rl
1 Like

@JeremyLT @k.satvx
Thanks

1 Like