skip to Main Content

I am pre-selecting a date on <input type='date' /> and want the user to select a date anyway. If the date selected is the same as the pre-selected value, it does not trigger the change event in jQuery.

Also tried blur and input, but it only activates when losing the focus of the element, not on date selection.

Any ideas how to achieve this?

The pre-selected date is a suggested date which can be chosen or another date could be chosen.

<input id="my-date" type="date" value="2024-07-20" />

// ..

$( '#container' ).on( 'change', '#my-date', function()
{
    console.log( 'selected date: ' + $( this ).val() );
});

2

Answers


  1. Instead of using the change event, you should try detecting if the date’s new value is the same as its old value.

    var old_value = "";
    
    $("#dateinput").val("2024-07-20");
    
    function check(){
      if (old_value != $("#dateinput").val()){
            alert("Value changed"); // Change this to your code
        old_value = $("#dateinput").val()
        }
        setTimeout(check, 10);
    }
    
    setTimeout(check, 10);
    <!DOCTYPE html>
    <html>
    
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
      <body>
    
        <input type="date" id="dateinput" value=""><br><br>
        <input type="submit" value="Submit">
    
      </body>
    
    </html>
    Login or Signup to reply.
  2. To trigger an event when the user selects a date on an , you can handle the click event on the date input even if the chosen date is the same as the pre-selected value. The change event doesn’t fire if the value remains the same, so we must manually trigger our custom event.

    Here’s how you can achieve this:

    • Capture the initial value when the input is clicked.
    • Compare the selected value with the initial value when the input loses focus.
    • Trigger a custom event if the values are the same.

    Here is the HTML code:

    <div id="container">
        <input id="my-date" type="date" value="2024-07-20" />
    </div>
    

    Here is the jQuery code:

    $(document).ready(function() {
        var initialDate = '';
    
        $('#my-date').on('focus', function() {
            initialDate = $(this).val();
        });
    
        $('#my-date').on('blur', function() {
            var selectedDate = $(this).val();
            if (selectedDate === initialDate) {
                $(this).trigger('date-selected');
            }
        });
    
        $('#my-date').on('date-selected change', function() {
            console.log('selected date: ' + $(this).val());
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search