Jquery.prop checkbox click preventDefault

Recently, I have been working with many checkboxes. I ran into this problem with a click event .prevenDefault(), and I tried to find a solution for this. In my case, I wanted to be able to decide whether it is possible to check or uncheck the box in accordance with other fields. Sometimes I even had to open a dialog before starting an event. It sounded easier than it turned out ...

In this jsFiddle you can see what the problem is and how I tried to solve it (see also the code below). Most answers involve using changes instead of clicking. But you cannot use .preventdefault().

$('div').off('change','.wtf').on('change', '.wtf', function(e) {
    //e.preventDefault();
    //return false;
    if($(this).prop('checked') == true) {
        alert('I am true now, but I must stay false');
        $(this).prop('checked', false);
    }
    else {
        alert('I am false now, but I must stay true');
        $(this).prop('checked', true);
    }
});

Is this the best solution? Or is there another way to make this checkbox until it can change its state?

: , , , "".

+5
2

- , change click , change event .

, click change .preventDefault(). , , .

, . :

$('input[type="checkbox"]').on('change', function () {
    var ch = $(this), c;
    if (ch.is(':checked')) {
        ch.prop('checked', false);
        c = confirm('Do you?');
        if (c) {
            ch.prop('checked', true);
        }
    } else {
        ch.prop('checked', true);
        c = confirm('Are you sure?');
        if (c) {
            ch.prop('checked', false);
        }
    }
});
+8

Spokey , return, confirm() true

$("input[name='status']").change(function(e){
       if ($(this).is(':checked')){
           msg = "{{__('The set status will be Active again! Are you sure?')}}"
           a = confirm(msg);
           if (a){
               return true;
           }
           $(this).prop('checked',false)
       }
       else{
           msg = "{{__('The set will be Inactive! Are you sure?')}}"
           a = confirm(msg);
            if (a){
               return true;
           }
           $(this).prop('checked',true);
       }
   })
0

All Articles