DigitalMoss
DigitalMoss

Reputation: 77

Disable selected items in multiple drop down lists

Setup

I have a list of drop down lists that are all identical (think row item in a grid). They can be added dynamically and all contain the same list of items. My client has requested that items that are selected in one list should be disabled in all of the other lists.

Everything works except the newly added lists do not have their items disabled (the existing ones do).

The Code

This is broken into a series of function calls but I have munged it here for easier viewing:

function DoTheStuff()
{
   enableAllTheDropDownItems(); //This works

   var allLists = $(".fooSelections");
   allLists.each(function(itemIndex, selectList){
      var selectedItems = $(".fooSelections option[selected='selected']");

      selectedItems.each(function(index, element) {
          var selectedValue = $(element).val();
          var parent = $(element).parent();

          //skips an item if it is the selectedItem of the current list
          if(parent.is(selectList)){  
              return true;
          }

          $("option[value*='" + selectedValue + "']", selectList).attr('disabled', 'disabled');

      });
   });

}

I am using Templates (Editor/Display) to show this partial view but essentially the Razor syntax that creates each Select list looks like this:

@Html.DropDownListFor(m => m.FooId, new SelectList(Model.Foos, "FooId", "FooName", Model.FooId), new { @class = "fooSelections" }) 

Handlers

I call this in the ajax call that adds a record and the change event of any of the select lists. As I stated before, it seems to work fine for any lists that existed when the Partial View was loaded (asp.NET MVC 4) but not for the items added dynamically (their lists are populated but all of the items are enabled). Even when a second dynamic item is added the first one (added in a different action) doesn't have its items disabled.

Question

Anyone see what I am missing? Or is there a better way to accomplish this same thing?

EDIT : Added missing bracket that Robin caught.

Upvotes: 0

Views: 502

Answers (1)

Robin Rizvi
Robin Rizvi

Reputation: 5183

I assume you are using razor ajax helper methods to do the ajax call.

In your ajax helper method @Ajax.ActionLink, you can provide a AjaxOptions object in which you can set a JS method to execute on the OnComplete property

Example:

@Ajax.ActionLink("linkText", "actionName", new AjaxOptions {UpdateTargetId = "DomID", OnComplete = "DoTheStuff" }) 

In case you are not using ajax helpers and using native ajax call or jquery ajax call, just call "DoTheStuff" method in the ajax success callback.

I improved your example and tested it in a fiddle. Please have a look at http://jsfiddle.net/eJudx/

Upvotes: 1

Related Questions