Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check/uncheck radio button onclick

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.

like image 329
DiegoP. Avatar asked May 31 '11 18:05

DiegoP.


1 Answers

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');   } }); 
like image 117
Jurrie Avatar answered Oct 06 '22 02:10

Jurrie