onclick for button not calling function

后端 未结 3 1492
失恋的感觉
失恋的感觉 2021-01-25 13:33

One of the problems I am experiencing at the moment is not being able to call a function in the onclick event of the submit button.

3条回答
  •  甜味超标
    2021-01-25 14:09

    As others have mentioned, the issue here is the scope that the validate() function is defined in.

    JavaScript is "lexically scoped", meaning that the location of a declaration determines from where it can be reached by other code.

    Your validate function is declared (scoped to) inside the anonymous document.ready function. This means that the only place where validate can be "seen" is by other code that shares that scope. The onclick=validate() line is outside of that scope and that is why your function isn't being called.

    However, instead of moving the validate() function outside of the document.ready() callback (thus making it global, which is a bad thing), you really should remove the onclick inline HTML event attribute as this is a bad practice (see this for several reasons why) and do the event binding in the script area. This approach will allow you to set up the event in the same scope as the validate() function and keep the HTML clean:

    $(document).ready(function() {
      // Do your event binding in JavaScript, not as inline HTML event attributes:
      $("#submit").on("click", validate);
    
      // Now the event handler reference and the function are in the same scope
      function validate() {
        var contactName = document.getElementById("contact-name").value;
        alert("Thank you " + contactName);
      }
    });
    
    

    Here's a bit more on scope.

提交回复
热议问题