5

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.

raoul1034
  • 187
  • 1
  • 1
  • 4
  • If you just need to get the value of the currently selected radiobox [see this discussion](http://stackoverflow.com/questions/596351/how-can-i-get-which-radio-is-selected-via-jquery). – emfurry May 27 '11 at 17:02
  • 1
    Not related to the question but you shouldn't have two elements with same ids. – Sang Suantak May 27 '11 at 17:07
  • Also not related to the question, but technically jQuery *requires* quotes around attribute selectors, e.g. `:radio[name="hasAcceptedAgreement"]` and you should also use === instead of == almost unequivocally. – Jamie Treworgy May 27 '11 at 17:52

3 Answers3

9

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.

Community
  • 1
  • 1
JoseV
  • 852
  • 10
  • 9
5

I used the code below in a project I worked on and it worked!

$(':radio[name=hasAcceptedAgreement]').change(function () {
    if ($('input[name=hasAcceptedAgreement]:checked').val() == 'True') {
        // display div
    } else {
        // hide div
    }
});
Yini
  • 691
  • 8
  • 9
1
$(function(){
   // executed once the dom is loaded

   // bind the change function as usual
   $(':radio[name=hasAcceptedAgreement]').change(function () {
        if ($(this).val() == 'True') {
            // display div
        } else {
            // hide div
        }
    }).change();  // and immediately trigger it
});

A small improvement for the change handler (so you don't need the if/else block)

$("#yourdiv").toggle( $(this).val() == 'True' );
roberkules
  • 6,557
  • 2
  • 44
  • 52