You can set the actions performed by submitting and reset buttons on a form within a <form> tag as below.
<form action="submitpage.html" onsubmit="return validate(this)"
onreset="return conform()" method="post">
<!--Other Form Elements-->
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
In the above code, when we click the submit button, it goes to the page “submitpage.html” after validating the form. It could be done by the function validate(). When we have clicked the reset button it clears all the form data after displaying confirmation box by the function conform().
When we click the button, it is easier to do any task on the clicking event of a button by executing certain JavaScript functions. There are different ways to execute JavaScript codes on button click. Hence, in this post, I am going to describe those different methods of clicking buttons using JavaScript.
Different Ways to Click Button Using JavaScript
You can click a button using JavaScript with the different methods given below.
With directly specifying JavaScript Built-in function on onClick event of Button
<input type="button" value="Display Time"
onClick="alert(new Date().toLocaleTimeString());">
By creating a JavaScript function and specifying it on the onClick event of Button. To know more about it, refer to the previous post: “How to create Timer Using JavaScript?“
<script>
var c=0
var t
function timedCount(){
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()", 1000)
}
</script>
<input type="button" value="Start Count" onClick="timedCount()">
<input type="button" value="0" id="txt">
We can create a JavaScript function along with specifying the onClick event of Button.
<script>
window.onload=function(){
var btn=document.getElementById('btn');
btn.onclick=function(){alert("You Have Clicked Button");}
};
</script>
<input type=button id='btn' value='click me'>
With specifying single function for multiple buttons having the same class name. It can be done by using for loop on the onClick event of a button.
<script>
window.onload=function(){
var btns=document.getElementsByClassName('bt');
for(var i=0; i<btns.length; i++){
var bt=btns[i];
bt.onclick=function(){alert("You Have Clicked Button");}
}
};
</script>
<input type=button class='bt' value='Button 1'>
<input type=button class='bt' value='Button 2'>
<input type=button class='bt' value='Button 3'>
In conclusion, we can add clicking events with a number of ways such as specifying JavaScript Built-in function on the onClick event, creating a JavaScript function and specifying a single function for multiple buttons having the same class name.
Read Next: How to go Back Browsing History Using JavaScript
Comments are closed.