Changing value attribute of radio buttons in a group using jQuery
11,667
Solution 1
Use the :not() selector. And, as you see, you also can use :checked to set the value to yes.
$(document).on("click","input[name=active]:radio",function(){
$("input:radio[name=active]:checked").val('yes');
$("input:radio[name=active]:not(:checked)").val('no');
});
Solution 2
Another way,
$(document).on("click","input[name=tab-active]:radio",function(){
$("input:radio[name=tab-active]:not(:checked)").val('no');
if($(this).is(':checked')) {
$(this).val('yes');
}
});
Author by
Addicted
Updated on June 16, 2022Comments
-
Addicted almost 2 years
I have multiple dynamically added radio buttons. I want to change the value attribute of selected radio button to
"yes"
and change the radio button value to"no"
once some other radio button is selected.<input type="radio" name="tab-active" value="no" />
I am able to get the value to change to
"yes"
by using the following jQuery:$(document).on("click","input[name=tab-active]:radio",function(){ if($("input:radio[name=tab-active]").is(":checked")) { $(this).val('yes'); } });
How can I change the value attribute of the selected radio button to
"no"
once some other radio button is selected? -
C_B over 10 years+1 for efficiency and for introducing me to the
:not()
selector.