Wednesday, February 20, 2019

javascript - jQuery checkbox change and click event






$(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?");
}
});
});









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.



This 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?


Answer



Tested in JSFiddle and does what you're asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked.



Updated Answer:




$(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);
});
});


Original Answer:



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


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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...