jQuery: make checkboxes act like radio buttons?

后端 未结 11 1647
栀梦
栀梦 2020-11-28 10:29

Is there a way to make checkboxes act like radio buttons? I assume this could be done with jQuery?



        
11条回答
  •  半阙折子戏
    2020-11-28 11:30

    The solution given doesn't care about the initial state, which is different from the radio buttons behavior. Plus, it also triggers a change event when clicking on an already checked input.

    var $elements = $('input:checkbox');
    
    // Allow only one input to be selected
    $elements.filter(':checked:not(:last)').prop('checked', false);
    
    // Get selected input
    var selected = $elements.filter(':checked')[0] || {};
    
    // Handle event
    $(document).on('click', 'input:checkbox', function(e) {
      if (e.currentTarget === selected) {
        e.preventDefault(); 
      } else {
        selected.checked = false;
        selected = e.currentTarget;
      }
    });
    
    
    
    
    
    

    I also agree that doing that is a bad idea, but if you have a different name for each input (and can't change them), there is no other choice...

提交回复
热议问题