views:

34

answers:

1

i have this code

<div id="aggregate" style="display:inline">
                    <%=Html.RadioButton("a", "1", true, new {id = "meRadio"})%><label>Me</label>
                    <%=Html.RadioButton("a", "2", false, new { id = "teamRadio" })%><label>Team: </label><% = Html.DropDownList("Teams", Model.Teams,  new {@scope="Team",  @id = "teamDropdown", @class = "filterDropdown" })%>
                    <%=Html.RadioButton("a", "4", false, new { id = "managerRadio" })%><label>Manager: </label><% = Html.DropDownList("Managers", Model.People, new { @scope = "Manager", @id = "managerDropdown", @class = "filterDropdown" })%>
                    <%=Html.RadioButton("a", "5", false, new { id = "locationRadio" })%><label>Location: </label><% = Html.DropDownList("Locations", Model.Locations, new { @scope = "Location", @id = "locationDropdown", @class = "filterDropdown" })%>
  </div>

i currently have code like this:

 $('#workstreamRadio').click(function () {
     Enable("#workstreamDropdown");
 });

 $('#teamRadio').click(function () {
     Enable("#teamDropdown");
 });

I am sure there is a way using jquery to dynamically get the respective dropdown selector given a specific radio button clicked so i dont have to hard code each mapping.

what is the syntax for saying "get me the selector of the dropdown to the right of the radio button i clicked"

+2  A: 

You can do it using .nextAll() and :first like this:

$("#aggregate :radio").change(function() {
  var dropdown = $(this).nextAll("select:first");
  //enable or disable dropdown
});

since they're siblings, use .nextAll() which goes through all siblings, and you want the first <select> element, so select that from the siblings after the radio clicked. Also look at using .change() here instead of .click(), it'll fire only when the selection changes, which is usually what you want here.

Nick Craver
@Nick Craver - will this handle the first entry which has no dropdown. i only want this to apply to all other radio buttons except the first one as the first one has slightly different logic. i was thinking of having a class attribute on all radio buttons except the first one to solve this.
ooo
@ooo - You can change the selector for binding, change `$("#aggregate :radio")` to `$("#aggregate :radio:gt(0)")` to ignore the first radio, and it won't be bound :)
Nick Craver
@Nick: why `nextAll('select:first')` and not `next('select')`?
Alexander Gyoshev
@Alexander - `.next()` finds *only* the *very* next element *if* it matches the selector...it doesn't continue to look until it finds one, it's a bit counter-intuitive.
Nick Craver
@Nick: oh. thanks, didn't know that, +1 :)
Alexander Gyoshev