简体   繁体   中英

JavaScript function called on checkbox change

Stuck at calling a simple JS function. Developer tools at chrome, console tab, thows

(index):591 Uncaught ReferenceError: checkbox is not defined at myFunction ((index):591) at HTMLInputElement.onclick

Code is

<span>Notificaciones</span>
    <input type="checkbox" id="myCheck" onclick="myFunction()">         
    <script type="text/javascript">
        function myFunction() {
              var checkBox = document.getElementById("myCheck");
              if(checkbox.checked){
                alert("suscribe");
              }  else{
                  alert("descuscribe");
              };
            };
    </script>

只需输入“ if(checkbox.checked){”,而不是“ if(checkBox.checked){”

It was a typo on checkbox and checkBox

 <span>Notificaciones</span> <input type="checkbox" id="myCheck" onclick="myFunction()"> <script type="text/javascript"> function myFunction() { var checkBox = document.getElementById("myCheck"); if(checkBox.checked){ alert("suscribe"); } else{ alert("descuscribe"); }; }; </script> 

Should work now :)

In the if statement that you have you put checkbox.checked which should be checkBox.checked .

<html>
<head>
   <script type="text/javascript">
      function myFunction() 
        {
        var checkBox = document.getElementById("myCheck");
        if(checkBox.checked)
        {
          alert("suscribe");
        }  
        else
        {
          alert("descuscribe");
        };
      };
   </script>
</head>
<body>
<span>Notificaciones</span>
    <input type="checkbox" id="myCheck" onclick="myFunction()">
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM