How to check/uncheck radio button on click?

后端 未结 18 1396
情深已故
情深已故 2020-11-29 02:16

I want to be able to uncheck a radio button by clicking on it.

So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.

<
18条回答
  •  温柔的废话
    2020-11-29 02:30

    I know this question is old, but I just came across this problem and decided to have a go myself and didn't want to use a modifier button like ctrl.

    See fiddle at http://jsfiddle.net/ArktekniK/yhbw469f/ For toggling a radio button by clicking on the radio button itself

    $('input[type=radio]').on('mousedown', function(e){
      var wasChecked = $(this).prop('checked');
      this.turnOff = wasChecked;
      $(this).prop('checked', !wasChecked);
    });
    
    $('input[type=radio]').on('click', function(e){
      $(this).prop('checked', !this.turnOff);
      this['turning-off'] = !this.turnOff;
    });
    

    For toggling a radio button by clicking on the label or radio button itself

    $('label:has(input[type=radio])').on('mousedown', function(e){
      var radio = $(this).find('input[type=radio]');
      var wasChecked = radio.prop('checked');
      radio[0].turnOff = wasChecked;
      radio.prop('checked', !wasChecked);
    });
    
    $('label:has(input[type=radio])').on('click', function(e){
      var radio = $(this).find('input[type=radio]');
      radio.prop('checked', !radio[0].turnOff);
      radio[0]['turning-off'] = !radio[0].turnOff;
    });
    

提交回复
热议问题