SomethingSomething
SomethingSomething

Reputation: 12176

JQueryUI's DatePicker - triggering show up from JS

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

Answers (4)

Want to be deleted
Want to be deleted

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

j08691
j08691

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');
})

jsFiddle example

Upvotes: 1

Unforgiven
Unforgiven

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

Rino Raj
Rino Raj

Reputation: 6264

show(): Opens the date picker.

$(document).ready(function(){
    $( "#datepicker" ).datepicker();
    $("button").click(function(){
        $("#datepicker").datepicker("show")
    });
});

Fiddle Demo

Upvotes: 1

Related Questions