Deniss A.
Deniss A.

Reputation: 1

How to determine if a specific radio button in a radio button group is checked?

I have a radio button group in my HTML form:

<form action="handler.php">
  <p><b>a or b or c</b></p>
  <p><input type="radio" id="abc" name="answer" value="a1">1<Br>
  <input type="radio" id="abc" name="answer" value="a2">2<Br>
  <input type="radio" id="abc" name="answer" value="a3">3</p>
 </form>

I want to check to see if a specific radio button (with value a1, for example) is checked, and then show a picture if it is:

<script>
function ShowPicture() {
  var word = document.getElementById("abc").value;

  if (word == "a1") {
      document.getElementById("demo").innerHTML = '<iframe src="http://picturesite.com/index" width="1024" height="720" align="left">';
  } 
}
</script>

How do I determine if the radio button is checked, so that I can use it in the condition used to display the image?

Upvotes: 0

Views: 85

Answers (2)

Jack jdeoel
Jack jdeoel

Reputation: 4584

id must be unique ,so your code is not working ! But I have two methods to for your problem .First one is get by name and second is get by tagname .This two function are return a list of nodes so need to loop ...

//var word = document.getElementsByName("answer"); //get by name
 var word = document.getElementsByTagName("input");//get element name
 for(var i =0;i<word.length;i++){
  if(word[i].value == "a1") {
  document.getElementById("demo").innerHTML = '<iframe src="http://picturesite.com/index" width="1024" height="720" align="left">';
  } 
}

Upvotes: 0

Ehsan
Ehsan

Reputation: 12959

This help you :

<html>
    <head>
    </head>
    <body>
        <form action="handler.php">
              <p><b>a or b or c</b></p>
            <p><input type="radio" class="abc" name="answer" value="a1" onchange="ShowPicture()">1</p>
            <p><input type="radio" class="abc" name="answer" value="a2" onchange="ShowPicture()">2</p>
            <p><input type="radio" class="abc" name="answer" value="a3" onchange="ShowPicture()">3</p>
        </form>
        <div id="demo"></div>
        <script>
           function ShowPicture() {
              var word = document.getElementsByClassName("abc");
              var len = word.length;
               for(var i=0;i< len-1; i++) {
                   if(word[i].value == "a1" && word[i].checked)
                   document.getElementById("demo").innerHTML = '<iframe src="http://picturesite.com/index" width="1024" height="720" align="left">'
                   
               }
            }
        </script>
    </body>
</html>

Upvotes: 1

Related Questions