menu

Questions & Answers

How to open datepicker on button click jquery

I am working on Jquery,Right now i am getting "datepicker" on "input type text",but i want to display that datepicker on button click,how can i do this ? Here is my current code

<head>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Initialize the datepicker and display a button panel underneath the calendar.</title>
</head>
<body>
<p>Pick a date:</p>   
<p><input type="text" id="datepicker1" /></p> 
<button id="bt">Date</button>
</body>


<script>
 $('#bt').click(function(){
        $( "#datepicker1" ).datepicker({
    showButtonPanel: true
});
});
</script>

Comments:
2023-01-23 23:01:13
Welcome to Stack Overflow. Please review: jqueryui.com/datepicker/#icon-trigger This is built in and you cna also make use of the .trigger("focus") in the event callback of the custom button if you prefer.
Answers(3) :

Based on the following: https://jqueryui.com/datepicker/#icon-trigger you can use the following example:

$(function() {
  $("#datepicker1").datepicker({
    showButtonPanel: true,
    showOn: "button",
    buttonText: "Date"
  });
});
.block>* {
  display: block;
  margin: 10px 0;
}
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
<div class="block">
  <label>Pick a date:</label>
  <input type="text" id="datepicker1" />
</div>

The button is added dynamically and retains the style format you showed with CSS.

use this code for open a date picker on click

$("#bt").click(function() {
        $(this).datepicker().datepicker( "show" )
    });

use this code for open a date picker on button click

$(document).ready(function () {
    $("#txtdate").datepicker({
        showOn: "button",
        buttonText: "Select date"
    });
    
});
   
<html>
<head>
    <title>DatePicker</title>
    <link href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="Stylesheet"
        type="text/css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    
</head>
<body>
    Date :
    <input id="txtdate" type="text">
</body>
</html>