Bootstrap Datepicker with Year selection

 68
Bootstrap Datepicker with Year selection

A year-only datepicker is a user-friendly way to allow users to select just a year. we will demonstrate how to implement a year picker using Bootstrap Datepicker.

Example:
Here is the complete example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Year Picker Example</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Datepicker CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/css/bootstrap-datepicker.min.css" />
</head>
<body>
    <div class="container mt-5">
        <h2>Select a Year</h2>
        <form action="/action_page.php">
            <div class="input-group mb-3">
                <input type="text" 
                       class="form-control" 
                       placeholder="Select year" 
                       name="year_of_business" 
                       id="year_of_business" 
                       readonly>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>

    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Bootstrap Datepicker JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/js/bootstrap-datepicker.min.js"></script>
    
    <script type="text/javascript">
        $(function() {
            $('#year_of_business').datepicker({
                format: "yyyy",               // Display only the year
                minViewMode: "years",         // Set minimum view to years
                autoclose: true,              // Automatically close the picker after selection
                startView: "years",           // Start with the year selection view
                startDate: '1800',            // Earliest year selectable
                endDate: new Date().getFullYear(), // Latest year selectable is the current year
            }).on('change', function() {
                let selectedYear = $(this).val();    // Get the selected year
                console.log("Selected Year: " + selectedYear);
            });
        });
    </script>
</body>
</html>

Post a Comment

0Comments

* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Post a Comment (0)