skip to Main Content

I am new to jquery but I managed to adapt code to my needs.
The idea is that I need a group of checkboxes where only 1 can be checked (radio buttons is not an option).

The following code works perfectly.

<!doctype html>
<html>
<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <table>   
        <tr >    
            <input type='checkbox' class='ART2' id='ART2_DE'>DE
            <input type='checkbox' class='ART2' id='ART2_EN'>EN   
            <input type='checkbox' class='ART2' id='ART2_FR'>FR   

            <script type="text/javascript"> 
                $('input.ART2').on('change', function(evt) {if($(this).siblings(':checked').length >= 1) { this.checked = false; }}); 
            </script>  

        </tr>   
    </table>
</body>
</html>

If I add data cells "< th >", the code doesn’t work anymore.

<!doctype html>
<html>
<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <table>   
        <tr >    
            <th><input type='checkbox' class='ART2' id='ART2_DE'>DE</th>   
            <th><input type='checkbox' class='ART2' id='ART2_EN'>EN</th>   
            <th><input type='checkbox' class='ART2' id='ART2_FR'>FR</th>   

            <script type="text/javascript"> 
                $('input.ART2').on('change', function(evt) {if($(this).siblings(':checked').length >= 1) { this.checked = false; }}); 
            </script>  

        </tr>   
    </table>
</body>
</html>

Can someone explain my why?

2

Answers


  1. <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <body>
        <table>   
            <tr>    
                <th><input type='checkbox' class='ART2' id='ART2_DE'>DE</th>   
                <th><input type='checkbox' class='ART2' id='ART2_EN'>EN</th>   
                <th><input type='checkbox' class='ART2' id='ART2_FR'>FR</th>   
            </tr>   
    
            <script type="text/javascript"> 
                $('input.ART2').on('change', function(evt) {
                    var checkboxes = $(this).closest('table').find('input.ART2');
                    checkboxes.not(this).prop('checked', false);
                }); 
            </script>  
        </table>
    </body>
    </html>
    
    Login or Signup to reply.
  2. Try this, Hope this will solve your problem

        $("input.ART2").on('click',function() { 
        if ($(this).prop('checked')==true)
            var thisId = $(this).attr('id');
            $("input.ART2").each(function() {
                if ($(this).attr('id')!=thisId){
                $(this).prop('checked', false);
                }
            });
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search