Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the currently selected value of a radio button with jQuery

In MVC, I can define a set of radio buttons like so:

@Html.RadioButtonFor(x => x.hasAcceptedAgreement, true) Yes
@Html.RadioButtonFor(x => x.hasAcceptedAgreement, false) No

which renders

<input id="hasAcceptedAgreement" name="hasAcceptedAgreement" type="radio" value="True" /> Yes
<input id="hasAcceptedAgreement" name="hasAcceptedAgreement" type="radio" value="False" /> No

I want to disable or enable a div based on what item is selected, which I've managed to do using this bit of jQuery:

$(':radio[name=hasAcceptedAgreement]').change(function () {
    if ($(this).val() == 'True') {
        // display div
    } else {
        // hide div
    }
});

But when they submit the form, I also need to have a check to see which value is currently selected, then show/hide the appropriate section again (since the .change function won't be called on POST). Is there a way I can accomplish that?

If I try to do if $(':radio[name=hasAcceptedAgreement]').val(), it will always evaluate to True since the ids are the same (I'm assuming). Is there some other way to get the value, or am I up creek because MVC likes to give the same name to each id?

EDIT: By the way, I am aware I can just manually set the ids in the RadioButtonFor call - I just wondered if there was some easier built-in way to handle it I wasn't aware of.

like image 487
raoul1034 Avatar asked May 27 '11 16:05

raoul1034


People also ask

How can I know which radio button is selected via jQuery?

To check which radio button is selected in a form, we first get the desired input group with the type of input as an option and then the value of this selection can then be accessed by the val() method. This returns the name of the option that is currently selected.

Which method can be used to obtain the value associated with the selected radio button in Python?

If we want to get the output to check which option the user has selected, then we can use the get() method. It returns the object that is defined as the variable.


1 Answers

As they say here: How can I get which radio is selected via jQuery? you may use:

$('input[name=hasAcceptedAgreement]:checked').val()

to get the value of the currently selected radio.

like image 136
JoseV Avatar answered Sep 27 '22 23:09

JoseV