[javascript] Simulating Button click in 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>

This question is related to javascript

The answer is


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

$('#foo').on('click', function() {
      alert($(this).text());
    });
$('#foo').trigger('click');

Use this

jQuery("input.second").trigger("click");

try this

document.getElementById("datapicker").addEventListener("submit", function())

The reason your code isn't working the way you would expect is because this line:

<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>

should be changed to:

<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>

There are two things to notice here:

1: The "s around datepicker have been changed to 's so that they do not interfere with the quotes surrounding the onclick event.

2: The click() has been changed to focus() to activate the datepicker calendar. When the button is pressed.

Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>, this should not be a problem.

Inline events are not recommended.


Or you can use what JQuery alreay made for you:

http://jqueryui.com/datepicker/#icon-trigger

It's what you are trying to achieve isn't it?


The smallest change to fix this would be to change

onClick="document.getElementById("datepicker").click()">

to

onClick="$('#datepicker').click()">

click() is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.