[javascript] jQuery checkbox change and click event

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  //set initial state._x000D_
  $('#textbox1').val($(this).is(':checked'));_x000D_
_x000D_
  $('#checkbox1').change(function() {_x000D_
    $('#textbox1').val($(this).is(':checked'));_x000D_
  });_x000D_
_x000D_
  $('#checkbox1').click(function() {_x000D_
    if (!$(this).is(':checked')) {_x000D_
      return confirm("Are you sure?");_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="checkbox1"/><br />_x000D_
<input type="text" id="textbox1"/>
_x000D_
_x000D_
_x000D_

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?

This question is related to javascript jquery checkbox event-handling

The answer is


$(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')) {
            if(!confirm("Are you sure?"))
            {
                $("#checkbox1").prop("checked", true);
                $('#textbox1').val($(this).is(':checked'));
            }
        }
    });
});

Demo

Use mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});

Late answer, but you can also use on("change")

_x000D_
_x000D_
$('#check').on('change', function() {
     var checked = this.checked
    $('span').html(checked.toString())
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="check"> <span>Check me!</span>
_x000D_
_x000D_
_x000D_


Try this

$('#checkbox1').click(function() {
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = sure;
            $('#textbox1').val(sure.toString());
        }
    });

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


<div id="check">
    <input type="checkbox" id="checkbox1" />
    <input type="text" id="textbox1" />
</div>

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)

<div id="OuterDivOrBody">
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox label</label>
    <br />
    <br />
    The confirm result:
    <input type="text" id="textbox1" />
</div>

In which case you could use:

Earlier versions of jQuery:

$('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with jQuery 1.6.4

jQuery 1.7+

$('#checkbox1').on('change', function() { 
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with the latest jQuery 2.x

  • Added jsfiddle examples and the html with the clickable checkbox label

For me this works great:

$('#checkboxID').click(function () {
    if ($(this).attr('checked')) {
        alert('is checked');
    } else {
        alert('is not checked');
    }
})

// this works on all browsers.

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

    $('#checkbox1').change(function(e) {
        this.checked =  $(this).is(":checked") && !!confirm("Are you sure?");
        $('#textbox1').val(this.checked);
        return true;
    });
});

Try

_x000D_
_x000D_
checkbox1.onclick= e => {
  if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
  textbox1.value = checkbox1.checked;
}
_x000D_
<input type="checkbox" id="checkbox1" /><br />
<input type="text" id="textbox1" value='false'/>
_x000D_
_x000D_
_x000D_


simply just use click event my check box id is CheckAll

     $('#CheckAll').click(function () {

        if ($('#CheckAll').is(':checked') == true) {

             alert(";)");
      }
    }

I am not sure why everyone is making this so complicated. This is all I did.

if(!$(this).is(":checked")){ console.log("on"); }

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.


 $("#person_IsCurrentAddressSame").change(function ()
    {
        debugger
        if ($("#person_IsCurrentAddressSame").checked) {
            debugger

        }
        else {

        }

    })

if you are using the iCheck Jquery use the below code

 $("#CheckBoxId").on('ifChanged', function () {
                alert($(this).val());
            });

Here you are

Html

<input id="ProductId_a183060c-1030-4037-ae57-0015be92da0e" type="checkbox" value="true">

JavaScript

<script>
    $(document).ready(function () {

      $('input[id^="ProductId_"]').click(function () {

        if ($(this).prop('checked')) {
           // do what you need here     
           alert("Checked");
        }
        else {
           // do what you need here         
           alert("Unchecked");
        }
      });

  });
</script>

Well .. just for the sake of saving a headache (its past midnight here), I could come up with:

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

Hope it helps


get radio value by name

 $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });

Try this:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }

Checkbox click and checking for the value in the same event loop is the problem.

Try this:

$('#checkbox1').click(function() {
    var self = this;
    setTimeout(function() {

        if (!self.checked) {
            var ans = confirm("Are you sure?");
            self.checked = ans;
            $('#textbox1').val(ans.toString());
        }
    }, 0);
});

Demo: http://jsfiddle.net/mrchief/JsUWv/6/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?