Set selected radio from radio group with a value
Asked Answered
T

12

192

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?
Trotskyite answered 6/1, 2011 at 19:7 Comment(0)
T
411

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 then you will be able to add checked property / attribute to one of the radio button in that radio buttons group.

Code To Remove Checked Attribute from all radio buttons of one radio button group -

$('[name="radioSelectionName"]').removeAttr('checked');
Track answered 6/1, 2011 at 19:9 Comment(10)
.prop('checked', true) is probably better or .is()Caprifoliaceous
@bladefist: .is wouldn't help here, but I agree with .prop. It wasn't available back then ;) Will update my answer. Thanks!Track
If the value of the radio button has a decimal, you need to put the value in quotesNoninterference
@Robert: Yep, probably. From the documentation: "Can be either an unquoted single word or a quoted string."Track
Isn't constructing a jquery selector programmatically like this prone to injection attacks? Is there a way to do it without needing to do this?Artair
See Jonathan's answer. The jQuery docs show that .val() supports setting values on radio or checkbox groups. This answer's way technically works, but is roundabout and much less readable/memorable.Ectogenous
prop() method is fine, but attr() method only works once, if you run it again for a different value the checked attr will appear twice and the first presents will be selected, attr() should not be used is this case.Cellophane
it should be $("input[name=registration][value=' + value + ']").prop('checked', true); instead of $("input[name='registration'][value=" + value + "]")Radbun
Removing all existing checked attributes first was the bit I was looking for/needed confirmation for.Lebron
To unselect all: $("input[name=mygroup]").prop('checked', false); --- removeAttr('checked') doesn't seem to work.Stoa
S
178

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/

Sw answered 25/3, 2014 at 13:13 Comment(3)
Accepted answer (well, should be). As of jQuery 1.0, see last example from docs (scroll to bottom): api.jquery.com/val Copied here: jsfiddle.net/JoePC/w1f9yksoRevolving
This is a nice and consistent way to set all input values. Too bad it's taken me 6 years to learn about it.Averse
Spent quite a while trying to figure out why all my values in the group were getting set to the passed value instead of checking the value. Turns out I passed the value by itself, not inside an array.Nonrestrictive
B
20

Try this:

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

JS Fiddle demo.

Bridgid answered 6/1, 2011 at 19:8 Comment(1)
@Hunter, thanks...today is clearly not my day for jQuery... =/Bridgid
L
10

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');
Launalaunce answered 15/7, 2015 at 22:58 Comment(0)
J
9
$("input[name='mygroup'][value='5']").attr("checked", true);
Johppah answered 6/1, 2011 at 19:11 Comment(0)
R
7

Pure JavaScript version:

document.querySelector('input[name="myradio"][value="5"]').checked = true;
Reexamine answered 31/12, 2019 at 11:51 Comment(0)
U
5

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

JS fiddle Demo

Uropod answered 23/12, 2017 at 6:35 Comment(0)
P
5

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(").

Proclus answered 2/6, 2021 at 6:39 Comment(0)
D
1

Or you can just write value attribute to it:

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

This works for me.

Danyelledanyette answered 26/6, 2015 at 9:22 Comment(0)
S
0
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);
   }
  })
}
Stadium answered 26/7, 2016 at 7:32 Comment(1)
Can you please explain what your code does in your answer? At least a sentence or so. And how it solves the solution. Thank you.Jedthus
C
0

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>
Conny answered 25/8, 2021 at 20:16 Comment(0)
K
-1
$('input[name="mygroup"]').val([5])
Kopje answered 17/10, 2019 at 9:19 Comment(2)
Can you explain what makes your solution different from the other solutions already provided?Sidewinder
@Giovani Vercauteren , we should give the name as a string. So I give the mygroup as a string in the code.Kopje

© 2022 - 2024 — McMap. All rights reserved.