dcolumbus
dcolumbus

Reputation: 9722

Set selected radio from radio group with a value

Why am I struggling with this?

I have a value: 5

How do I check the radio button of group "mygroup" with the value of 5?

$("input[name=mygroup]").val(5); // doesn't work?

Upvotes: 194

Views: 362587

Answers (12)

Felix Kling
Felix Kling

Reputation: 816790

With the help of the attribute selector you can select the input element with the corresponding value. Then you have to set the attribute explicitly, using .attr:

var value = 5;
$("input[name=mygroup][value=" + value + "]").attr('checked', 'checked');

Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

$("input[name=mygroup][value=" + value + "]").prop('checked', true);

Remember you first need to remove "checked" attribute from any of radio buttons under one radio buttons group (only one button can be checked at a time); only then you will be able to add "checked" property / attribute to one of the radio buttons in that radio buttons group.

Code to remove "checked" attribute from all radio buttons in a radio button group:

$('[name="radioSelectionName"]').removeAttr('checked');

Upvotes: 415

vsync
vsync

Reputation: 130421

First way assumes there is already a saved reference for the radio group (inputs): group and it is wished to select one in the group, by value

const group = document.querySelectorAll('input[name="contact"]');

function selectGroupByValue(group, value){
  const input = [...group].find(el => el.value === value);
  if(input) input.checked = true;
}

selectGroupByValue(document.querySelectorAll('input[name="contact"]'), 'phone');
<input type="radio" name="contact" value="email">
<input type="radio" name="contact" value="phone">
<input type="radio" name="contact" value="mail">

This can be taken a step further, to create a more robust function which can change the value of a any group, by its name:

function selectGroupByValue(name, value){
  const group = document.querySelectorAll(`input[name="${name}"]`);
  const input = [...group].find(el => el.value === value);
  if(input) input.checked = true;
}

selectGroupByValue('contact', 'phone');
<input type="radio" name="contact" value="email">
<input type="radio" name="contact" value="phone">
<input type="radio" name="contact" value="mail">

The below example is completely different as it does not have a cached reference to the radio group, but does a lookup every time:

const selectedValue = 'phone';
const input = document.querySelector(`input[name="contact"][value="${selectedValue}"`);
if(input) input.checked = true;
<input type="radio" name="contact" value="email">
<input type="radio" name="contact" value="phone">
<input type="radio" name="contact" value="mail">

If the group is within a <form> element: (intentionally did not break the for iterator)

for (const [index, input] of document.forms[0].contact.entries())
  if(input.value === `phone`)
    input.checked = true
<form>
  <input type="radio" name="contact" value="email">
  <input type="radio" name="contact" value="phone">
  <input type="radio" name="contact" value="mail">
</form>

Upvotes: 1

Dinushika Rathnayake
Dinushika Rathnayake

Reputation: 419

I got an error when using

$("input[name=mygroup][value="value"]").prop('checked', true);

Working way is

$("input[name=mygroup][value='value']").prop('checked', true);

The issue is handling quotes(') and double quotes(").

Upvotes: 7

JukkaV
JukkaV

Reputation: 81

Pure JavaScript version:

document.querySelector('input[name="myradio"][value="5"]').checked = true;

Upvotes: 8

Anjitha
Anjitha

Reputation: 59

$('input[name="mygroup"]').val([5])

Upvotes: -1

Jonathan Pasquier
Jonathan Pasquier

Reputation: 2591

There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value

Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.

$("input[name=mygroup]").val([5]);

Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value

And .val([...]) also works with form elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>.

The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected

Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/

Upvotes: 180

karan
karan

Reputation: 71

$("input[name='RadioTest'][value='2']").prop('checked', true);

JS fiddle Demo

Upvotes: 5

Amin Fathi
Amin Fathi

Reputation: 9

var key = "Name_radio";
var val = "value_radio";
var rdo = $('*[name="' + key + '"]');
if (rdo.attr('type') == "radio") {
 $.each(rdo, function (keyT, valT){
   if ((valT.value == $.trim(val)) && ($.trim(val) != '') && ($.trim(val) != null))

   {
     $('*[name="' + key + '"][value="' + (val) + '"]').prop('checked', true);
   }
  })
}

Upvotes: 0

Jean-Marc Amon
Jean-Marc Amon

Reputation: 989

When you change attribute value like mentioned above the change event is not triggered so if needed for some reasons you can trigger it like so

$('input[name=video_radio][value="' + r.data.video_radio + '"]')
       .prop('checked', true)
       .trigger('change');

Upvotes: 11

Ketan
Ketan

Reputation: 11

Or you can just write value attribute to it:

$(':radio[value=<yourvalue>]').attr('checked',true);

This works for me.

Upvotes: 1

David Thomas
David Thomas

Reputation: 253396

Try this:

$('input:radio[name="mygroup"][value="5"]').attr('checked',true);

JS Fiddle demo.

Upvotes: 21

hunter
hunter

Reputation: 63532

$("input[name='mygroup'][value='5']").attr("checked", true);

Upvotes: 9

Related Questions