0

I have a group of radio buttons and I want to add functionality that allows a user to deselect all radios by clicking on the radio that is currently selected.

E.g. by default the first radio is checked. The user then clicks on the second radio which then becomes select. The user now decides that actually no radio should be selected at all and clicks the second radio again to remove all selections.

The problem is that with a change or click event I'm not able to determine of a radio was checked before the user clicked it.

Is there a way to determine if a radio button was previously checked or not?

4

2 回答 2

3

Easy - store the most recently clicked button in a Javascript variable

于 2013-06-28T01:17:47.443 回答
1

You can add an attribute to the radio button like

<input type="radio" data-checked="true">

and then all radio buttons with that attribute will be accesible via

$("input:radio[data-checked]")

you can add a listener that will add that attribute like so:

$(function(){
   $('input').change(function(){
      if($(this).attr('data-checked')){
          $(this).removeAttr('data-checked');
      } else {        
          $(this).attr('data-checked', 'true');
      }
   })
})
于 2013-06-28T01:17:39.637 回答