RadioButtonListFor and jQuery

One requirement I received for a recent ASP.NET MVC form implementation was that particular radio buttons be checked on the basis of other radio buttons being checked. Because it’s a relatively simple form, I opted to fulfill the requirement with just jQuery instead of adding knockout.js as a dependency.

Our HTML helper for radio button lists is not much different than this one.  So the first task was to identify whether or not the radio button checked was the one that should trigger another action.  As has always been the case when grouping radio buttons in HTML, each radio button in the group shares the same name and differs by id and value.  The HTML looks kind of like this:

@Html.RadioButtonListFor(m => m.Choice.Id, Model.Choice.Id, Model.ChoiceListItems)

where ChoiceListItems is a list of System.Web.Mvc.SelectListItem and the ids are strings.  The jQuery to see if a radio button in the group has been checked looks like this:

$("input[name='Choice.Id']").change(function(){
...
}

Having determined that a radio button in the group has been checked, we must be more specific and see if the checked radio button is the one that should trigger additional action. To accomplish this, the code snippet above is changed to the following:

$("input[name='Choice.Id']").change(function(){
if($("input[name='Choice.Id']:checked").val() == '@Model.SpecialChoiceId'){
...
}
}

The SpecialChoiceId value is retrieved from the database. It’s one of the values used when building the ChoiceListItems collection mentioned earlier (so we know a match is possible). Now the only task that remains is to check the appropriate radio button in the second grouping. I used jQuery’s multiple attribute selector for this task.  Here’s the code:

$("input[name='Choice.Id']").change(function(){
 if($("input[name='Choice.Id']:checked").val() == '@Model.SpecialChoiceId'){
  $("input[name='Choice2.Id'][value='@Model.Choice2TriggerId']").prop('checked',true);
 }
}

The first attribute filter selects the second radio button group, the second attribute filter selects the specific radio button, and prop(‘checked’,true) adds the ‘checked’ attribute to the HTML. Like SpecialChoiceId, Choice2TriggerId is retrieved from the database (RavenDB in our specific case).