Addicted
Addicted

Reputation: 149

Changing value attribute of radio buttons in a group using jQuery

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?

Upvotes: 2

Views: 12132

Answers (4)

Rajesh Paul
Rajesh Paul

Reputation: 7009

$("input[name='tab-active']").change(function()
    {
        $("input[name='tab-active']").val('no');
        $(this).val('yes');
    }
)

Fiddle demo

Upvotes: 0

msapkal
msapkal

Reputation: 8346

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');
    }
});

DEMO

Upvotes: 1

Bhavesh Parekh
Bhavesh Parekh

Reputation: 212

you can make html tags like

<input type="radio" id="1" name="tab-active"  /><span id="lbl1">no</span>
<input type="radio" id="2" name="tab-active" /><span id="lbl2">no</span>
<input type="radio" id="3" name="tab-active"  /><span id="lbl3">no</span>

And the js code like

$(document).on("click","input[type:radio]",function(){    
    if($("input:radio[name=tab-active]").is(":checked")) {
       $("#lbl" + $(this).attr('id')).html("yes");   
    }
});

You can check it in this link http://jsfiddle.net/nkvak/

Hope it will help you

Upvotes: 0

Markus Kottl&#228;nder
Markus Kottl&#228;nder

Reputation: 8268

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');
});

JSFiddle

Upvotes: 10

Related Questions