JQuery checkbox on change and checked event

0 votes
$(document).ready(function() { 
    //set initial state. 
    $('#textbox1').val($(this).is(':checked')); 
  
    $('#checkbox1').change(function() { 
    $('#textbox1').val($(this).is(':checked')); 
}); 

$('#checkbox1').click(function() { 
  if (!$(this).is(':checked')) { 
    return confirm("Are you sure?"); 
      } 
  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<input type="checkbox" id="checkbox1"/><br /> 
<input type="text" id="textbox1"/>

Here .change() updates the textbox value with the checkbox status. I use .click() to confirm the action on uncheck. If the user selects cancel, the checkmark is restored but .change() fires before confirmation which leaves things in an inconsistent state and the textbox says false when the checkbox is checked. How can I deal with the cancellation and keep textbox value consistent with the check state?

Feb 23, 2022 in Java-Script by Soham
• 9,730 points
66,599 views

1 answer to this question.

0 votes

Have shared an approach which will add the benefit of firing when a label associated with a checkbox is clicked. 

$(document).ready(function() { 
        //set initial state. 
        $('#textbox1').val(this.checked); 

        $('#checkbox1').change(function() { 
          if(this.checked) { 
              var returnVal = confirm("Are you sure?"); 
              $(this).prop("checked", returnVal); 
    } 
    $('#textbox1').val(this.checked); 
    });
});

answered Feb 23, 2022 by Aditya
• 7,680 points
0 votes
asfasdfadsfasdfdffasdfads
answered Jun 30, 2022 by anonymous
• 120 points

edited Mar 5

Related Questions In Java-Script

0 votes
1 answer

jQuery AJAX fires error callback on window unload - how do I filter out unload and only catch real errors?

Hello, In the error callback or $.ajax you have three ...READ MORE

answered Apr 27, 2020 in Java-Script by Niroj
• 82,800 points
5,043 views
0 votes
3 answers
0 votes
1 answer

How to set “checked” for a checkbox with jQuery?

Hello @kartik, Use: $(".myCheckbox").attr('checked', true); // Deprecated $(".myCheckbox").prop('checked', true); And if ...READ MORE

answered Aug 28, 2020 in Java-Script by Niroj
• 82,800 points
6,872 views