1

I have two radio buttons. One is checked by default but I want to uncheck that one and check an other one by default.

So I have this HTML:

<div class="gui-radio">
  <input type="radio" value="register" name="choise" id="new-register">
  <label for="register">Register</label>
</div>
<div class="gui-radio">
  <input type="radio" checked="checked" value="guest" name="choise" id="new-guest">
  <label for="new-guest">Guest</label>
 </div>

This all automatically generated. I need this to be done with Jquery.

So How do I uncheck the second one and check the first one?

kapa
  • 77,694
  • 21
  • 158
  • 175
Meules
  • 1,349
  • 4
  • 24
  • 71

3 Answers3

2

jQuery 1.6+

You can check a checkbox by setting .prop('checked', true); and uncheck it by setting .prop('checked', false);.

$('#new-register').prop('checked', true);
$('#new-guest').prop('checked', false);

jQuery 1.5 and below

$('#new-register').attr('checked','checked');
$('#new-guest').removeAttr('checked');
AfromanJ
  • 3,922
  • 3
  • 17
  • 33
  • It would be better to use `$('#new-register').prop('checked', true);` and `$('#new-guest').prop('checked', false);` as Checked is a property – Nunners Dec 18 '13 at 13:33
1

They are already connected by their name attributes, so all you need to do is make the first one checked - the second one will automatically become unchecked, because in a radio group only one can be selected.

This is how you make a radio/checkbox checked in jQuery:

$('#new-register').prop('checked', true);
Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
1

This checks the first radio:

jQuery('input#new-register').prop('checked', true);

Also closing the inputs might be a good idea:

<div class="gui-radio">
    <input type="radio" value="register" name="choise" id="new-register" />
    <label for="register">Register</label>
</div>
<div class="gui-radio">
    <input type="radio" checked="checked" value="guest" name="choise" id="new-guest" />
    <label for="new-guest">Guest</label>
</div>

jsfiddle link

MaGnetas
  • 4,918
  • 4
  • 32
  • 52