Check/Uncheck - ifChecked not working

心不动则不痛 提交于 2019-12-08 03:40:28

问题


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" />

回答1:


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/




回答2:


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");
    }

});



回答3:


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/



来源:https://stackoverflow.com/questions/33900838/check-uncheck-ifchecked-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!