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?
This question is related to
jquery
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/
$("input[name='RadioTest'][value='2']").prop('checked', true);
$("input[name='mygroup'][value='5']").attr("checked", true);
Pure JavaScript version:
document.querySelector('input[name="myradio"][value="5"]').checked = true;
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');
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);
}
})
}
Or you can just write value attribute to it:
$(':radio[value=<yourvalue>]').attr('checked',true);
This works for me.
$('input[name="mygroup"]').val([5])
Source: Stackoverflow.com