Search code examples
jqueryalertsweetalert2

can't pick date again in datepicker modal after swal fire alert


My HTML:

<input type="text" id="start" class="form-control" value="">
<input type="text" id="end" class="form-control" value="">
<input type="text" id="pay" class="form-control" value="">

My JS:

$(document).ready(function () {
    $("#start,#end").bootstrapMaterialDatePicker({

        startView: "days",
        autoclose: true,
        format: "DD MMMM YYYY", 
        weekStart: 0, 
        time: false,    
    });

    $("#end").change(function () {
    var startDate = document.getElementById("start").value;
    var endDate = document.getElementById("end").value;
 
    if ((Date.parse(endDate) <= Date.parse(startDate))) {
        // alert("End date should be greater than Start date"); //default alert
         $('#end').modal('toggle'); //hide modal when end date is smaller than start date
        Swal.fire({                 //trigger the swal alert

            icon: 'error',

            title: 'Validation',

            text: 'End date should be greater than Start date',


        });
        $('#end').modal('show'); //after alert, input the end date again (not working)
        document.getElementById("end").value = "";
    }
    });
}

Screenshot:

enter image description here

The validation process worked, but when I clicked OK, the alert didn't immediately close, and I can't select the date in datepicker modal again.

enter image description here

I tried $('#end').modal('toggle'); and $('#end').modal('show'); but it's not working.

Question: How can I hide the alert modal, and select the date again?

Any help would be appreciated.


Solution

  • Your code has some issues :

    1. Change event is fired when the user clicks the ok button. it will automatically close the date picker, so you don't need to manually close it. (Note that Swal.fire is async.)

    2. you shouldn't manually close/open the datepicker modal, it breaks the event handlers in it. instead you can open the datepicker with $("#date").focus();

    3. Swal.fire is async and returns a promise. so you shouldn't put the code for reopening datapicker next to it, instead you should use Swal.fire(...).then(v => {...}).

    Full code (Run the code on codepen):

    $("#date").bootstrapMaterialDatePicker({
        format: "DD/MM/YYYY",
        lang: "fr",
        weekStart: 1,
        time: false,
        startView: "days",
        autoclose: true
    });
    
    $("#date").change(function (e) {
        Swal.fire({
            icon: "error",
            title: "Validation",
            text: "End date should be greater than Start date"
        }).then((v) => {
            $("#date").focus();
        });
    });