简体   繁体   中英

Select only one checkbox HTML

I have a problem with checking only one checkbox... I tried two types of JS code.. But it doesn't work... To check by class, when u click on one element with class 'product-list' to deselect another... Have someone idea how to solve this?

HTML:

<div class="mg-toolbar">
  <div class="mg-option checkbox-custom checkbox-inline">
    <input class="product-list" type="checkbox" name="PDF" value="<?php echo $file_name; ?>">
    <label for="file_1">SELECT</label>
  </div>
</div>

JS Try 1:

<script type="text/javascript">
   $('.product-list').click(function() {
     $(this).siblings('input:checkbox').prop('checked', false);
   );
</script>

JS Try 2:

<script type="text/javascript">
   $('.product-list').on('change', function() {
     $('.product-list').not(this).prop('checked', false);  
   });
</script>

If you want to ensure that only one item to be selected at once, then actually that's what radio buttons were invented for (rather than checkboxes). And you don't need any JS code to make that work.

Demo:

 <div class="mg-toolbar"> <div class="mg-option checkbox-custom checkbox-inline"> <input class="product-list" id="file_1" type="radio" name="PDF" value="File1"> <label for="file_1">SELECT 1</label> </div> <div class="mg-option checkbox-custom checkbox-inline"> <input class="product-list" id="file_2" type="radio" name="PDF" value="File2"> <label for="file_2">SELECT 2</label> </div> <div class="mg-option checkbox-custom checkbox-inline"> <input class="product-list" id="file_3" type="radio" name="PDF" value="File3"> <label for="file_3">SELECT 3</label> </div> <div class="mg-option checkbox-custom checkbox-inline"> <input class="product-list" id="file_4" type="radio" name="PDF" value="File4"> <label for="file_4">SELECT 4</label> </div> </div>

change the #c01 and #c02 to the two check box ID's your doing this with. I think this may do what you need it to do. If c01 checked, c02 is unchecked, and vice-versa

 $("#c01").click(function(){
        if($("#c01").is(':checked'))
        $("#c02").prop("checked", false);
    });
    
    $("#c02").click(function(){
        if($("#c02").is(':checked'))
        $("#c01").prop("checked", false);
    });

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