Check/Uncheck - ifChecked not working

2019-06-02 08:35发布

UPDATE: I'm using the following plugin

I'm trying to check if the checkbox is checked when the user refresh the page or reload the page and here is what I have used but I have done the debugging and it never execute the second IF condition

$('input').on('ifChecked', function (event) {
    if ($("input#CreatePart").is(':checked')) {
        alert('checked');
    }
});

$('input').on('ifUnchecked', function (event) {
    if ($("input#CreatePart").is(':checked')) {
        alert('un-checked');
    }
});

<input checked="checked" class="icheck" data-val="true" 
  data-val-required="The Create new Part field is required." 
  id="CreatePart" name="CreatePart" type="checkbox" value="true" 
/>
<input name="CreatePart" type="hidden" value="false" />

3条回答
【Aperson】
2楼-- · 2019-06-02 09:12

Try:

on page load:

 alert($('input').is(':checked'));

http://jsfiddle.net/9ypwjvt4/18/

else use:

   $(document).ready(function () {
    $('input').iCheck({
        checkboxClass: 'icheckbox_square-orange',
        radioClass: 'iradio_square-orange',
        increaseArea: '20%' // optional
    });

    $('input').on('ifChecked', function(event){
      alert('Checked');
    });

    $('input').on('ifUnchecked', function(event){
      alert('unchecked');
    });
});

jsfiddle: http://jsfiddle.net/9ypwjvt4/17/

查看更多
▲ chillily
3楼-- · 2019-06-02 09:16

Use on change event instead on using ifChecked or ifUnchecked

$('input.icheck').on('change', function (event) {
    if ($("input#CreatePart").is(':checked')) {
        alert('checked');
    }else{
       alert("unchecked");
    }

});
查看更多
我想做一个坏孩纸
4楼-- · 2019-06-02 09:20

Change your condition on ifUnchecked to make sure the checkbox is NOT checked instead of checked.

You were checking to see if the box is checked when the unchecked event is fired which that would never happen.

$('input').on('ifUnchecked', function (event) {
    if ($("input#CreatePart").not(':checked')) {
        alert('un-checked');
    }
});

DEMO:

http://jsfiddle.net/ejLbgt7b/

查看更多
登录 后发表回答