vendredi 23 avril 2021

Checkbox not working normally in case of event.preventDefault and just working when using setTimeout

I was just going through a scenario where I needed to customize a checkbox so that it can be checked and unchecked not instantly, but when some button is clicked. While working on that, I used preventDefault followed by stopPropagation to stop the checkbox from following default behavior and make it check or uncheck conditionally.

The checkbox is getting checked at first, but then it is not un-checking, given the code is working fine with setTimeout but not without it. Following is the mockup:

window.message = 'Some message that appears on modal';
$(document).ready(function() {
  $('#chkbx').off('click').on('click', function(e) {
    var $checkbox = $(this);
    e.preventDefault();
    e.stopPropagation();
    console.log($checkbox.is(':checked') ? 1 : 0);
    showConfirmation($checkbox.is(':checked') ? 1 : 0);
  });

  function showConfirmation(s_checked) {
    // Why this if block is making checkbox checked 
    if (s_checked) {
    // in place of settimeout, in actual code we are showing a modal having 
    // yes and no buttons, on the click of yes we call a callback function, 
    // in which we check the checkbox and do other necessary UI changes tasks
      setTimeout(function() {
        $('#chkbx').val(1);
        $('#chkbx').prop('checked', true);
      });
      // While a similar code without delay is not working
    } else {
        // Line 24 and 25 code does not unchecks the checkbox
      $('#chkbx').val(0);
      $('#chkbx').prop('checked', false);
      
      // But line 27 to 31 code does unchecks the checkbox
      /* setTimeout(function() {
        $('#chkbx').val(0);
        $('#chkbx').prop('checked', false);
      }); */

    }
    return true;
  }
})

Please help me understand, what is going wrong here due to which the code is not unchecking the checkbox when not using setTimeout.




Aucun commentaire:

Enregistrer un commentaire