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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With