jQuery check/uncheck radio button onclick

DiegoP. picture DiegoP. · May 31, 2011 · Viewed 238.6k times · Source

I have this code to check/uncheck a radio button onclick.

I know it is not good for the UI, but I need this.

$('#radioinstant').click(function() {     
  var checked = $(this).attr('checked', true);
  if(checked){ 
    $(this).attr('checked', false);
  }
  else{ 
    $(this).attr('checked', true);
  }
});

The above function is not working.

If I click on the button, nothing changes. It remain checked. Why? Where is the error? I am not a jQuery expert. I am on jQuery 1.3.2

Just to be clear #radioinstant is the ID of the radio button.

Answer

Jurrie picture Jurrie · Jun 11, 2012

I have expanded on the previous suggestions. This works for me, with multiple radios coupled by the same name.

$("input[type='radio']").click(function()
{
  var previousValue = $(this).attr('previousValue');
  var name = $(this).attr('name');

  if (previousValue == 'checked')
  {
    $(this).removeAttr('checked');
    $(this).attr('previousValue', false);
  }
  else
  {
    $("input[name="+name+"]:radio").attr('previousValue', false);
    $(this).attr('previousValue', 'checked');
  }
});