Web Designing Tutorials

How to Click Button Using JavaScript?

Google+ Pinterest LinkedIn Tumblr
Buttons on a web-page allows users to submit data or to do any action on it and generally the actions are performed by clicking on it. Different types of buttons are used on web-page and they may be inside a form or outside a form for certain action to be performed. Buttons used within a form may be Submit Button, Reset Button, Browse Button etc.
You can set the actions performed by submit and reset buttons on a form with in 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 submit button was clicked it goes to the page “submitpage.html” after validating the form by the function validate() and when reset button was clicked it clears all the form data after displaying conformation box by the function conform().
It is easier to do any task on clicking event of a button by executing certain JavaScript functions when the button was clicked. There are different ways to execute JavaScript codes on button click. In this post I am going to describe about those different methods of clicking buttons using JavaScript.

Different Ways to Click Button Using JavaScript

You can click 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());">
Preview:

With creating a JavaScript function and specifying it on onClick event of Button as given on 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">

 

Preview:
 
var c=0var tfunction timedCount()

{

document.getElementById(‘txt’).value=c

c=c+1

t=setTimeout(“timedCount()”, 1000)

}

With creating a JavaScript function along with specifying 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'>
Preview:
 
window.onload=function(){var btn=document.getElementById(‘btn’);btn.onclick=function(){alert(“You Have Clicked Button”);}

var btns=document.getElementsByClassName(‘bt’);

for(var i=0; i

Shuseel Baral is a web programmer and the founder of InfoTechSite has over 5 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Write A Comment