Open In App
Related Articles

How to show calendar only click on icon using JavaScript ?

Improve Article
Improve
Save Article
Save
Like Article
Like

Bootstrap is one of the widely preferred CSS frameworks for the development of an interactive user interface. Bootstrap comes bundled with a wide range of components, plugins, and utilities that make designing a webpage much easier. 

The date-picker is one such interactive feature provided by Bootstrap to select a date from a drop-down calendar which is directly reflected in the input field eliminating the hassle to enter the date manually. The date picker can be customized as per user requirements. Whether the calendar opens in a form of a drop-down on clicking the icon only or focussing on the input field entirely, depends on the need of the user. However, both options are open for one to choose from. The drop-down calendar is available as a small overlay and automatically disappears once the user clicks anywhere outside the calendar on the web page. This functioning of the calendar is made possible through jQuery and JavaScript functions. Below are the examples for Date-picker which displays the calendar when clicked on the icon. 

Approach 1:

  • The calendar icon is appended to the input field where the date is to be input using the input-group-prepend class.
  • The span for the icon is set using the input-group-text class.
  • The icon when clicked triggers the setDatepicker() function and the setDatepicker() function accepts the current event as an argument.
  • Next, the class name of the root (parent) of the icon is obtained using the parent() and attr() methods of JavaScript. As the class name is obtained next the space in the class name is replaced by ‘.’.
  • This step is important as the class name is required in the class selector in the jQuery datepicker() function. The datepicker() function specifies the format of the date, the orientation of the calendar, closing, and autofocus behavior. Once the calendar is displayed the user can choose the date and it is reflected in the input field.

Example: This example shows the use of the above-explained approach

html




<!DOCTYPE html>
<html>
<head>
    <!-- Importing jquery cdn -->
    <script src=
    </script>
  
    <script src=
        integrity=
"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous">
    </script>
  
    <script src=
        integrity=
"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous">
    </script>
  
    <!-- Importing icon cdn -->
    <link rel="stylesheet" href=
  
    <!-- Importing core bootstrap cdn -->
    <link rel="stylesheet" href=
        integrity=
"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
        crossorigin="anonymous">
  
    <script src=
        integrity=
"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous">
    </script>
  
    <!-- Importing datepicker cdn -->
    <script src=
    </script>
</head>
  
<body>
    <!-- Container class contains the date field -->
    <div class="container" style="max-width: 250px;">
        <div class="form-group m-1">
            <label class="font-weight-bold" for="dob">
                Date of Birth:
            </label>
  
            <!-- Input field along with 
                calendar icon and -->
            <div class="input-group date">
                <!-- Sets the calendar icon -->
                <span class="input-group-prepend">
                    <span class="input-group-text">
                        <i class="fa fa-calendar" 
                            onclick="setDatepicker(this)">
                        </i>
                    </span>
                </span>
  
                <!-- Accepts the input from calendar -->
                <input class="form-control" type="text" 
                    name="dob" id="dob" value="">
            </div>
        </div>
    </div>
  
    <!-- JavaScript to control the actions
         of the date picker -->
    <script type="text/javascript">
        function setDatepicker(_this) {
  
            /* Get the parent class name so we 
                can show date picker */
            let className = $(_this).parent()
                .parent().parent().attr('class');
  
            // Remove space and add '.'
            let removeSpace = className.replace(' ', '.');
  
            // jQuery class selector
            $("." + removeSpace).datepicker({
                format: "dd/mm/yyyy",
  
                // Positioning where the calendar is placed
                orientation: "bottom auto",
                // Calendar closes when cursor is 
                // clicked outside the calendar
                autoclose: true,
                showOnFocus: "false"
            });
        }
    </script>
</body>
</html>


Output

Date-picker using Javascript

Date-picker using Javascript

Approach 2: The second approach is comparatively easier. It accomplishes the target in fewer lines of code. This code mainly makes use of jQuery. 

  • The date-picker button Image also serves the same purpose as the icon in the previous example. The buttonImageOnly does not only add an image to the button but it also adds an image to the document. 
  • As we click on the image the calendar is displayed and the user can select the date which is immediately reflected in the input field. The button image in this is pre-downloaded and stored in the local device. The calendar closes when clicked outside the calendar.

Example: This example shows the use of the above-explained approach

html




<html>
<head>
    <!-- Importing jquery cdn -->
    <link href=
        rel="Stylesheet"
        type="text/css" />
  
    <script type="text/javascript" 
    </script>
  
    <script type="text/javascript" 
    </script>
  
    <!-- JavaScript function to display the calendar -->
    <script language="javascript">
        $(document).ready(function () {
            $("#txtdate").datepicker({
                showOn: "button",
  
                // Button image stored on local device
                buttonImage: "./icons8-calendar-48.png",    
                buttonImageOnly: true
            });
        });
    </script>
  
    <!-- Customizing the datepicker button image -->
    <style type="text/css">
        .ui-datepicker-trigger { 
            max-height: 28px;
        }
    </style>
</head>
  
<body>
    <form class="form-group">
        Date :
        <input id="txtdate" type="text" 
            class="form-control">
    </form>
</body>
</html>


Output

jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 17 Jan, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials