Search code examples
javascriptdom-events

Checking if checkboxes and radios are checked


I've been through nearly every answer on this topic and I've had a hard time coming up with a solution.

Basically, I'm trying to click a button that runs a function which checks to see if a radio button or check box is selected.

Later one I'd like to be able to test for different combinations of these selections.

This is the code.

<html>
<head>
  <script type = "text/javascript">
    function custom_urls(){
      var option1 = document.getElementById("option1");
      var option2 = document.getElementByid("option2");
      var bonus = document.getElementByid("bonus");                                          

      if ( option1.checked ){
        alert("Option1 is checked!");
      }
    }


  </script>
</head>
<body>
  <input type = "radio" id = "option1" > Option1 </input></br>
  <input type = "radio" id = "option1" value = "option2"> Option2 </input></br>
  <input type = "checkbox" id = "bonus" value = "bonus"> Bonus </input></br>
  <button type = "button" onclick = "custom_urls()">Click Me</button> 

</body>
</html>

I've also tried putting:

if(option1.checked == true)

and

if(document.getElementById("option1").checked == true)

Solution

  • Looks like your code has typos. It must be document.getElementById:

    <html>
    <head>
      <script type = "text/javascript">
        function custom_urls(){
          var option1 = document.getElementById("option1");
          var option2 = document.getElementById("option2");
          var bonus = document.getElementById("bonus");                                          
    
          if (option1.checked){
            alert("Option1 is checked!");
          }
        }
    
    
      </script>
    </head>
    <body>
      <input type = "radio" id = "option1" > Option1 </input></br>
      <input type = "radio" id = "option2" value = "option2"> Option2 </input></br>
      <input type = "checkbox" id = "bonus" value = "bonus"> Bonus </input></br>
      <button type = "button" onclick = "custom_urls()">Click Me</button>
    
    </body>
    </html>