Reputation: 5
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.
Upvotes: 0
Views: 71
Reputation: 370619
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);
Upvotes: 1