Home > database >  Select only one checkbox HTML
Select only one checkbox HTML

Time:04-28

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 >
  <div >
    <input  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>

CodePudding user response:

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 >
  <div >
    <input  id="file_1" type="radio" name="PDF" value="File1">
    <label for="file_1">SELECT 1</label>
  </div>
  <div >
    <input  id="file_2" type="radio" name="PDF" value="File2">
    <label for="file_2">SELECT 2</label>
  </div>
  <div >
    <input  id="file_3" type="radio" name="PDF" value="File3">
    <label for="file_3">SELECT 3</label>
  </div>
  <div >
    <input  id="file_4" type="radio" name="PDF" value="File4">
    <label for="file_4">SELECT 4</label>
  </div>
</div>

CodePudding user response:

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);
    });
  • Related