I have
<input type="checkbox" id="checkbox1" /> <br />
<input type="text" id="textbox1" />
and
$(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 the changed event updates the textbox value with the checkbox status. I use the click event to confirm the action on uncheck. If the user selects cancel, the check mark is restored but the change even fires before confirmation leaving things in a inconsistent state (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?
get radio value by name
Well .. just for the sake of saving a headache (its past midnight here), I could come up with:
Hope it helps
if you are using the iCheck Jquery use the below code
Checkbox click and checking for the value in the same event loop is the problem.
Try this:
Demo: http://jsfiddle.net/mrchief/JsUWv/6/
Most of the answers won't catch it (presumably) if you use
<label for="cbId">cb name</label>
. This means when you click the label it will check the box instead of directly clicking on the checkbox. (Not exactly the question, but various search results tend to come here)In which case you could use:
Earlier versions of jQuery:
JSFiddle example with jQuery 1.6.4
jQuery 1.7+
JSFiddle example with the latest jQuery 2.x
Get rid of the change event, and instead change the value of the textbox in the click event. Rather than returning the result of the confirm, catch it in a var. If its true, change the value. Then return the var.