Check and Uncheck Checkbox Dynamically with jQuery : bug?

前端 未结 5 2246
我在风中等你
我在风中等你 2021-02-13 02:08

I made a script in order to control master & slave checkboxes (automatic checking and unchecking).

Here is my JS :

$(document).ready(function() {

           


        
相关标签:
5条回答
  • 2021-02-13 02:33

    Use prop method for new versions of jQuery:

    $('#myCheck').prop('checked', true);
    $('#myCheck').prop('checked', false);
    

    http://jsfiddle.net/uQfMs/37/

    0 讨论(0)
  • 2021-02-13 02:36

    i made some experiences , actually $(':checkbox').attr('checked',false); althought this could set the "checked" attribute , but it won't continuesly shows in the visual . and $(':checkbox').prop('checked', true); this one works perfectly! hope this could do some help .

    0 讨论(0)
  • 2021-02-13 02:37

    I wrote you a plugin for this:

    $.fn.dependantCheckbox = function() {
      var $targ = $(this);
      function syncSelection(group, action) {
        $targ.each(function() {
          if ($(this).data('checkbox-group') === group) {
            $(this).prop('checked', action);
          }
        });
      };
      $('input[type="checkbox"][data-checkbox-group]').on('change', function() {
        var groupSelection = $(this).data('checkbox-group');
        var isChecked = $(this).prop('checked');
        syncSelection(groupSelection, isChecked);
      });
    }
    $('input[type="checkbox"][data-checkbox-group]').dependantCheckbox();
    
    
    <input data-checkbox-group="1" type="checkbox" id="test" />
    <label for="test">test</label>
    <input data-checkbox-group="1" type="checkbox" id="test2" />
    <label for="test2">test2</label>
    <input data-checkbox-group="2" type="checkbox" id="test3" />
    <label for="test3">test3</label>
    <input data-checkbox-group="2" type="checkbox" id="test4" />
    <label for="test4">test4</label>
    

    http://codepen.io/nicholasabrams/pen/mJqyqG

    0 讨论(0)
  • 2021-02-13 02:46

    You could try this.

    $('#myCheck').click(function() {
        var checkBoxes = $(this).siblings('input[type=checkbox]');
        checkBoxes.prop('checked', $(this).is(':checked') ? true : false);
    });
    
    0 讨论(0)
  • 2021-02-13 02:46

    Maybe you just want to check the master checkbox:

    $('#myCheck').click(function() {
           $('.myCheck').attr('checked', false);
           $(this).attr('checked', true);
    });
    

    see this fiddle.

    0 讨论(0)
提交回复
热议问题