简体   繁体   中英

Javascript function not firing with html onclick

I am battling to get my javascript function to fire when a button is clicked on my html page. My html code snippet:

<!DOCTYPE html>
    <html>
        <head>
        <title>VLA SYSTEM</title>
        <a href="logout.php" onclick="logout();" style="float:right;">Logout</a>
        <script
            type ="text/JavaScript" src="logout.js"></script>

        </head>
    <body>
<form>
      <script
          type ="text/JavaScript" src="regGen.js"></script>
          <script
          type="text/JavaScript" src="submit.js"></script>
<input type="button" name="btnAssign" value="Assign Owner To Registration Number..." onclick="submit()">

My javascript code snippet:

function submit() {
    window.alert("Information Captured And Stored To Database!");
}

The idea is that, when the user clicks on the button, the alert should fire informing the user that information has been captured, however, I am unable to get this alert to appear.

Any advice would be greatly appreciated.

The problem is that, unintuitively, inline handlers essentially implicitly use with (this) for the element that triggered the event, and for the parent element, and so on:

 <form> <input type="button" name="btnAssign" value="Assign Owner To Registration Number..." onclick="console.log(submit === document.querySelector('form').submit)" > </form> 

And form.submit is a built-in function will submit the form.

Either use a different function name, like doAlert :

onclick="doAlert()"

and

function doAlert() {
  window.alert("Information Captured And Stored To Database!");
}

Or attach the listener properly using Javascript instead (inline handlers are pretty bad practice, and can result in unintuitive behavior like you're seeing):

document.querySelector('input[name="btnAssign"]).addEventListener('click', submit);

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