making checkboxes behave like radio buttons

后端 未结 2 1221
深忆病人
深忆病人 2021-01-16 04:05

Please see this: http://gisdev.clemson.edu/fireflies

Toward the top right are three checkboxes and I am trying to make them work like radio buttons. Part of the prog

相关标签:
2条回答
  • 2021-01-16 04:14

    The essential problem here is that you need to group a set of boxes and then if any one of the set is clicked, iterate through the set, unchecking all except the one that was clicked.

    You can group using a class name. Then give each an id.

    When the class is clicked, save the id of the clicked one. Then iterate through the checkboxes within the class and uncheck any that have a different id than the one you saved off.

    <form action="">
        <input id="cbBike" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Bike" checked>I have a bike<br />
        <input id="cbCar" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Car">I have a car<br />
        <input id="cbBoth" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Both">I have both<br />
        <input id="cbNeither" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Neither">I have neither<br />
    </form>
    
    
    var selectedBox = null;
    
    $(document).ready(function() {
        $(".CB2RBVehicles").click(function() {
            selectedBox = this.id;
    
            $(".CB2RBVehicles").each(function() {
                if ( this.id == selectedBox )
                {
                    this.checked = true;
                }
                else
                {
                    this.checked = false;
                };        
            });
        });    
    });
    

    Here's an example.

    0 讨论(0)
  • 2021-01-16 04:27

    If you want checkboxes to act as radio buttons, attach onClick event listeners to all checkboxes, remove "checked" attributes and place it on the one being clicked.

    checkboxes_controls = jQuery(document.querySelectorAll('.leaflet-control-layers-overlays input[type=checkbox]'))
    
    jQuery(checkboxes_controls).click(function(){
        jQuery(checkboxes_controls).removeAttr('checked');
        jQuery(this).attr('checked', 'checked');
    });
    
    0 讨论(0)
提交回复
热议问题