简体   繁体   中英

How to disable or inactive checkbox when select current in jQuery

I want to disable other checkbox when current checkbox is checked or selected.

Following is my code. I have tried but not work

HTML

<input type="checkbox" name="test" id="test" class="test">One
<input type="checkbox" name="test" id="test" class="test">Two
<input type="checkbox" name="test" id="test" class="test">Three
<input type="checkbox" name="test" id="test" class="test">Four
<input type="checkbox" name="test" id="test" class="test">Five

JQuery Script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){

        $(".test").each(function(){
            if($(this).is(':checked')){
                $(this).prop('checked',true);
                $('.test').prop('checked',false);
            }
        })
    })  
</script>

You can make use of change event handler and read :checked value of the checkbox clicked. Disable or enable other checkboxes as per :checked value

See below code

NOTE: Always use unique ids for all HTML elements otherwise you will end up with wrong result for the jquery script with id selectors

 $(document).ready(function(){ $(".test").on('change', function(){ $('.test').not(this).prop('disabled', $(this).is(':checked')); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="test" id="test1" class="test">One <input type="checkbox" name="test" id="test2" class="test">Two <input type="checkbox" name="test" id="test3" class="test">Three <input type="checkbox" name="test" id="test4" class="test">Four <input type="checkbox" name="test" id="test5" class="test">Five

First you need to use click or change event, then you don't need to use $(this).prop('checked',true); and do not use duplicate id

 $('.test').click(function() { let $this = $(this); if ($this.is(':checked')) { $('.test').not($this).attr('disabled', true) } else { $('.test').attr('disabled', false) } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label><input type="checkbox" name="test" class="test">One</label> <label><input type="checkbox" name="test" class="test">Two</label> <label><input type="checkbox" name="test" class="test">Three</label> <label><input type="checkbox" name="test" class="test">Four</label> <label><input type="checkbox" name="test" class="test">Five</label>

For make disable you need to use 'disabled', true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM