GrantaOmega GrantaOmega - 5 months ago 6
HTML Question

JavaScript is Preceding Operation Before Clicking the "Submit" Button/Link

I am new to JavaScript, and I am having a little difficulty getting my operation to perform correctly. The program is running my code before I click on my submit button. There are many similar questions that have been covered so far, but I don't believe any of them have covered this exact issue. Please refrain from flagging this as answered elsewhere (believe me, I read those documents). Thanks in advance for the help.

<html>
<body style="background-color: lightgrey">
<link rel='stylesheet' type='text/css' href='newcss.css'/>
<ol>
<p style="color:black">Scan Location</p>
</ol>

<table class="scanLocation" align="center">
<tr>
<td>
<ol>
<input type="text" name="fname" maxlength= "18" size= "33" input style="font-size:20px"/>

</ol>
</td>
</tr>
<tr>
<td>
<ol>
<form>
<input type="button" onclick="script" value="Submit"/>
<p id="seconds"></p>
<script>
firstFunction();
function firstFunction(){
var date = new Date();
var seconds = date.getUTCSeconds();
myFunction();
function myFunction(){
document.getElementById("seconds").innerHTML = "seconds";
}
checkEven();
function checkEven(seconds){
return Math.floor(seconds%2) == Math.floor(0);
}
if(checkEven(seconds)){
location.href='index2.jsp';
}
else{
location.href='index3.jsp';
}
}
</script>
</form>
</ol>
</td>
</tr>
</table>
</body>
<script type='text/javascript' src='script.js'></script>
</html>

Answer

The script is executed exactly as you've written it. The problem is that you didn't specify onclick event correctly, the right version is:

<input type="button" onclick="firstFunction()" value="Submit"/>

And you should remove function call from the script itself, I mean this line right after opening script tag:

firstFunction();

In general it isn't the best option to bind an event as you HTML which should be just a presentation is dealing with the behavior as well, in a complex project it will be a pain to manage such pages but perhaps for the sake of studying it's fine.

Comments