Reputation: 12176
I want to let the datepicker show when I click on some button.
Using the official usage example, I've already succeeded creating a sample datepicker object, and to show it when user clicks on the datepicker's text box, with this code:
<p>Date: <input type="text" id="datepicker"></p>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
But I want a click on some button to trigger the date picker. I tried something like:
<button type="button" onclick = "showDatePicker()">click me</button>
<script>
function showDatePicker() {
document.getElementById('datepicker').datepicker();
}
</script>
But, it does not work at all.
Is there any way to trigger it from JS on demand?
Upvotes: 0
Views: 198
Reputation: 136
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<button id="bar" type="button">click me</button>
<p>Date: <input type="text" id="datepicker"></p>
<script>
//edit, forgot this
$('#datepicker').datepicker();
$('#bar').on('click',function(){
$('#datepicker').datepicker("show");
});
</script>
Fiddle: https://jsfiddle.net/2kp8tcfc/1/
Upvotes: 1
Reputation: 207901
Create your datepicker first, then use the button's click event to trigger the datepicker's show method:
$('#datepicker').datepicker();
$('button').click(function() {
$('#datepicker').datepicker('show');
})
Upvotes: 1
Reputation: 331
Simple. Just call the datepicker
method whenever the click event is triggered on the element of your choice.
You could either have the method display its own button, by adding some options to your first call of datepicker
$("#datepicker").datepicker({
showOn: 'button',
buttonImage: 'images/calendar.gif',
buttonImageOnly: true
});
or, just add a button
to your markup, then, in your javascript
$("#myButton").click(function() {
$("#datepicker").datepicker("show");
});
for further reading I refer you to this similar question Using jQuery Date picker with a custom trigger button
Upvotes: 1