Binding two checkboxes together

后端 未结 3 472
粉色の甜心
粉色の甜心 2021-01-14 23:01

I have two checkboxes

 

and



        
3条回答
  •  粉色の甜心
    2021-01-14 23:37

    Sure that's possible, but why would you have two checkboxes if they behave the same? Maybe one checkbox would be more convenient. :)

    Well, anyway, with a piece of jQuery this should work fine. This snippet allows you to give a checkbox a group, so it automatically selects others in the same group.

    Of course you could easily change this into a list of ids for example, so the behaviour doesn't need to be two ways, but I couldn't fully deduce from your question what you need. Anyway, adding extra checkboxes just requires them to have the right attribute.

    Because it uses the on function this way, it should even work for checkboxes that are dynamically added.

    $(document).on('click', 'input[type="checkbox"][data-group]', function(event) {
      // The checkbox that was clicked
      var actor = $(this);
      // The status of that checkbox
      var checked = actor.prop('checked');
      // The group that checkbox is in
      var group = actor.data('group');
      // All checkboxes of that group
      var checkboxes = $('input[type="checkbox"][data-group="' + group + '"]');
      // All checkboxes excluding the one that was clicked
      var otherCheckboxes = checkboxes.not(actor);
      // Check those checkboxes
      otherCheckboxes.prop('checked', checked);
    });
    
    
    
    
    
    
    
    

提交回复
热议问题