Categories
JavaScript Answers

How to make jQuery Datepicker close datepicker after selected date?

Spread the love

To make the jQuery Datepicker close automatically after a date is selected, you can use the onSelect event handler to trigger the closing action.

To do this we can write

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Datepicker Example</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
    $(document).ready(function() {
        // Initialize the Datepicker
        $("#datepicker").datepicker({
            onSelect: function(dateText, inst) {
                $(this).datepicker("hide"); // Close the Datepicker after selection
            }
        });
    });
</script>
</head>
<body>
    <p>Select a date:</p>
    <input type="text" id="datepicker">
</body>
</html>

In this code, the onSelect event handler is attached to the Datepicker input field.

When a date is selected, the onSelect function is triggered.

Inside the onSelect function, $(this).datepicker("hide") is used to hide/close the Datepicker popup after a date is selected.

This way, the Datepicker will automatically close after the user selects a date.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *