Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating Button click in javascript

Tags:

javascript

So what i want to do is when i click on a button, it will pass this click event to another element in webpage, or you can say it will create a new click event in another element. Below is my code, it does not work, please let me know what is wrong with it, it looks make sense...

<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.8.3.js"></script> <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css" /> <script> $(function() { $( "#datepicker" ).datepicker(); });    </script> </head> <body> <p>Date: <input type="text" id="datepicker" onClick=alert("error") /></p> <button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button> </body> </html> 
like image 352
ouyadi Avatar asked Jan 28 '13 19:01

ouyadi


People also ask

How do you make a button click itself in JavaScript?

You use document. getElementById("button-id"). click() to click your button.

How do you click something in JavaScript?

click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do you simulate a button in click in jest?

To simulate a button click in Jest, we can call the simulate method. to call shallow to mount the Button component. Then we call find with 'button' to find the button element. And then we call simulate with 'click' to simulate a click on it.

How do you trigger a button click event?

A single click event bind to a button with an Id of “button2”. and a trigger to execute the button1 click event handler. $("#button2"). bind("click", (function () { alert("Button 2 is clicked!"); $("#button1").


2 Answers

Since you are using jQuery you can use this onClick handler which calls click:

$("#datepicker").click() 

This is the same as $("#datepicker").trigger("click").

For a jQuery-free version check out this answer on SO.

like image 54
Matt Zeunert Avatar answered Oct 11 '22 02:10

Matt Zeunert


To simulate an event, you could to use trigger JQuery functionnality.

$('#foo').on('click', function() {       alert($(this).text());     }); $('#foo').trigger('click'); 
like image 30
sdespont Avatar answered Oct 11 '22 04:10

sdespont