626

$(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.

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?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Professor Chaos
  • 7,900
  • 7
  • 33
  • 52
  • 1
    It works in FF and chrome and has the explained behavior in IE 8. So it may be important to note which browsers you need this to work in and which ones you're seeing the error. – kasdega Aug 11 '11 at 18:56
  • It's not the best, but I believe it's working for me here: [http://jsfiddle.net/Skooljester/2Xxcn/](http://jsfiddle.net/Skooljester/2Xxcn/). – ayyp Aug 11 '11 at 19:00

20 Answers20

1002

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'));        
    });
});
callmebob
  • 5,000
  • 5
  • 24
  • 40
kasdega
  • 16,576
  • 12
  • 40
  • 83
  • 133
    Just a note, it's much faster to use `this.checked` instead of `$(this).is(':checked')`: http://jsperf.com/prop-vs-ischecked/5 – Dakota Jul 07 '14 at 17:39
  • 39
    @Dakota Granted, it is much slower, but we're still talking 600k operations/sec. So, 600 times per millisecond. I think if this starts causing performance issues on your web page, you might need to re-eval your javascript ;) It is good to understand performance metrics with code, though. Thanks. – Mike U Jan 08 '15 at 15:47
  • 54
    @MikeU: Agree with you on the premature optimization, but considering that `this.checked` is much shorter to write + native javascript, it might be really worth using in general (apart from being ~200 to 300 times faster). – Levite Mar 18 '15 at 10:37
  • 12
    I would recommend .prop() instead of .attr() since the latter does not work in all cases and I believe that jQuery recommend .prop() now. – kabadisha Jun 05 '16 at 16:28
  • @RyanMcArthur no, it's returning current state. – Marko Mackic Jan 12 '17 at 12:31
  • @MarkoMackic You're right, mis-read that. Deleted my comment to avoid causing any confusion, thanks. – Ryan McArthur Jan 20 '17 at 08:57
  • 2
    I think that [this] in $('#textbox1').val(this.checked); refers to document. It should be $('#textbox1').val($('#checkbox1').is(':checked')); – yurin Mar 10 '18 at 15:01
96

Demo

Use mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});
Community
  • 1
  • 1
Joseph Marikle
  • 68,672
  • 14
  • 103
  • 120
  • It displays the alert when checking it and it always prevents me from checking in fact. This is on Chrome. – pimvdb Aug 11 '11 at 18:54
  • same as @pimvdm. The confirmation pops up even for check-action (it should only pop up for uncheck) and selecting ok does not result in checking the box. – Professor Chaos Aug 11 '11 at 18:57
  • @Joseph: Thanks for the edit but the textbox does not change. – pimvdb Aug 11 '11 at 18:58
  • @pimvdb oh! textbox? that's not the main issue :P – Joseph Marikle Aug 11 '11 at 18:59
  • @Joseph the confirmation comes up on check with `mousedown`. Can it be changed so it comes up on uncheck? – Professor Chaos Aug 11 '11 at 19:05
  • OK, upvote :) Though checking using the keyboard is a workaround for the confirm now. – pimvdb Aug 11 '11 at 19:05
  • 1
    It works when using the mouse, but not if you are checking it with the keyboard. – frinux Feb 22 '13 at 11:17
  • 3
    @frinux That's quite simply because _it's a mouse related question._ Please don't downvote answers based on their relevance to entirely separate issues. If you have a problem triggering the state of an indicator after a checkbox check via keyboard, please post a question about it instead of downvoting answers carelessly. – Joseph Marikle Feb 22 '13 at 15:07
  • Joseph, do you know if this solution works for a blind person accessing the page? I was told in another context to stay away from mouse events because it makes it difficult for blind people to use the page. – kasdega Aug 28 '13 at 01:14
  • @kasdega I, unfortunately, am not an expert in that area, but I would venture to guess that it is not a good solution for that situation. I'm not sure how screen readers handle forms. I imagine they use the keyboard spacebar to select or deselect checkboxes, in which case I would say either use a keydown event or better yet ignore the issue and leave it to the changed event. The issue here was that of the checkbox *looking* checked before you confirmed or canceled. Such aesthetics would not be important to someone using a screen reader. – Joseph Marikle Aug 29 '13 at 02:33
  • what we do incase on selecting checkbox with label..?` ` – Vivek Vikranth Feb 13 '14 at 12:47
  • @VivekVikranth You can just add the same event to the label. You could get fancy and determine the appropriate radio button when the event is triggered, but for demonstration purposes, here is a simple example: http://jsfiddle.net/4DqXv/888/ – Joseph Marikle Feb 13 '14 at 17:38
  • 3
    Downvoted since mousedown is not the only way a user can interact with the checkbox. – Jonathan Aug 14 '17 at 10:01
55

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
lko
  • 7,631
  • 9
  • 37
  • 57
  • 1
    It is #OuterDivOrBody not .OuterDivOrBody :) – Laurent Brieu Aug 02 '17 at 08:16
  • I know this is SUPER OLD but I came across it looking for something else and wanted to let you know that in the second example (I didn't check the first fiddle) if the person clicks cancel, you are still unchecking and showing false, if they cancel then it should leave it check and say true. Just in case you want to fix it. – GµårÐïåñ Jun 23 '20 at 17:50
25

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

zarun
  • 859
  • 9
  • 25
11

For me this works great:

$('#checkboxID').click(function () {
    if ($(this).attr('checked')) {
        alert('is checked');
    } else {
        alert('is not checked');
    }
})
chris
  • 4,555
  • 5
  • 30
  • 53
  • 4
    Came across this via a web search. You should use 'prop' instead of 'attr' >> http://api.jquery.com/prop/ – Dr Schizo Aug 20 '13 at 13:30
11

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>
DmitryBoyko
  • 32,983
  • 69
  • 281
  • 458
8

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

$('#check').on('change', function() {
     var checked = this.checked
    $('span').html(checked.toString())
});
<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>
Pedro Lobito
  • 75,541
  • 25
  • 200
  • 222
6

if you are using the iCheck Jquery use the below code

 $("#CheckBoxId").on('ifChanged', function () {
                alert($(this).val());
            });
umer
  • 726
  • 1
  • 8
  • 27
6

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.

yoozer8
  • 6,966
  • 6
  • 47
  • 84
6

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/

Mrchief
  • 70,643
  • 19
  • 134
  • 181
5

Try this

$('#checkbox1').click(function() {
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = sure;
            $('#textbox1').val(sure.toString());
        }
    });
ShankarSangoli
  • 67,648
  • 11
  • 84
  • 121
5
$(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'));
            }
        }
    });
});
Jason
  • 654
  • 5
  • 10
  • 17
5
// 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;
    });
});
Marcelo De Zen
  • 8,957
  • 3
  • 32
  • 48
4
$('#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>
user3636759
  • 96
  • 1
  • 6
1

simply just use the click event my check box id is CheckAll

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

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

             alert(";)");
      }
    });
Geeti
  • 43
  • 8
1

get radio value by name

 $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });
Siva Anand
  • 2,712
  • 2
  • 15
  • 9
1

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

if(!$(this).is(":checked")){ console.log("on"); }
Char
  • 178
  • 1
  • 15
0

Try

checkbox1.onclick= e => {
  if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
  textbox1.value = checkbox1.checked;
}
<input type="checkbox" id="checkbox1" /><br />
<input type="text" id="textbox1" value='false'/>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
0

Try this:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }
Zahra Badri
  • 738
  • 8
  • 17
-2
 $("#person_IsCurrentAddressSame").change(function ()
    {
        debugger
        if ($("#person_IsCurrentAddressSame").checked) {
            debugger

        }
        else {

        }

    })
  • 3
    Code-only answers are considered low quality: make sure to provide an explanation what your code does and how it solves the problem. It will help the asker and future readers both if you can add more information in your post. See also Explaining entirely code-based answers: https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers – borchvm Jan 29 '20 at 06:57