Check Uncheck and disable CheckBox based on another in jQuery

Last Reply 3 months ago By dharmendr

Posted 3 months ago

hello,

i am using this bootstrap on off button wrap with checkbox

i want javascript that when checkbox1 is checked so checkbox2 is disabled and unchecked. and when checkbox1 is unchecked so checkbox2 become enable and on value change of checkbox1 bind the checked or unchecked status to label.

please advice

<label class="switch pull-right">
    <input type="checkbox" id="chkPassport" />
    <span class="slider round"></span>
</label>
<label class="switch pull-right">
    <input type="checkbox" id="chkPassport1"  />
    <span class="slider round"></span>
</label>
Posted 3 months ago Modified on 3 months ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

HTML
<label class="switch pull-right">
    <input type="checkbox" id="chkPassport" class="Passport" />
    <span class="slider round"></span>
</label>
<label class="switch pull-right">
    <input type="checkbox" id="chkPassport1" class="Passport" />
    <span class="slider round"></span>
</label>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('.Passport').on('change', function () {
            var chk1 = $('[id$=chkPassport]');
            var chk2 = $('[id$=chkPassport1]');
            var id = $(this).attr('id');
            if ($(chk1).attr('id') == id) {
                if ($(chk1).is(':checked')) {
                    $(chk1).closest('label').find('span').html('true');
                    $(chk2).closest('label').find('span').html('false');
                    $(chk2).attr("checked", false);
                    $(chk2).attr("disabled", true);
                }
                else {
                    $(chk2).attr("disabled", false);
                    $(chk1).closest('label').find('span').html('false');
                }
            }
            else {
                $(chk2).closest('label').find('span').html($(chk2).is(':checked') ? 'true' : 'false');
            }
        });
    });    
</script>

Demo