How to check/uncheck radio button on click?

后端 未结 18 1379
情深已故
情深已故 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条回答
  •  -上瘾入骨i
    2020-11-29 02:17

    As HexInteractive mentioned, radio button is handled outside the normal event chain. So, following example judges the button state by class name, not by property.

    var $self;
    
    $('input[type=radio]').on('click', function() {
      $self = $(this);
      if ( $self.hasClass('is-checked') ) {
        $self.prop('checked', false).removeClass('is-checked');
      } else {
        $self.addClass('is-checked');
      }
    });
    

提交回复
热议问题