jQuery Set + Unset Radio Buttons

Sam Deering

Simple jQuery code snippets to set and unset input values on radio buttons. Just thought I would share because I was having a few issues with earlier versions of jQuery and setting radio buttons on a form.

//jQuery Set Radio Button
$('input[name="correctAnswer"]').attr('checked', false);

//To unselect the button
$("[name=color]").removeAttr("checked");

//jQuery (1.4+) code to pre-select one button :
var presetValue = "black";
$("[name=color]").filter("[value="+presetValue+"]").attr("checked","checked");

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Kalana Nissanka

    Q1. Is there any way to create the label of the radio button dynamically?

    Q2. How can we get the checked value from a radio button group?

    • jquery4u

      Hi Kalana,

      1. Yes you can create a label element and insert it before the radio button like so (not tested):

      var labelText = $(‘#radioBtnId’).attr(‘name’);
      $(‘‘).insertBefore(‘#radioBtnId’);

      2. Try this:

      $(‘input:radio[name=theme]:checked’).val();

      or when it is selected try:

      $(“input:radio[name=theme]“).click(function() {
      var value = $(this).val();
      });

      Cheers
      Sam