Find non-matches in HTML select list against JSON list using Jquery

142 views Asked by At

I have a SelectList coming back from my MVC ActionResult as Json data:

the controller:

  public JsonResult _ConnectorFilters(string arg1, string arg2, string arg3) {
      //collecting selectlist items ex: 
      listConatenated.Add(newSelectListItem {Value = "Category1", Text = "attribute1"};
      listConatenated.Add(newSelectListItem {Value = "Category1", Text = "attribute2"}
      listConatenated.Add(newSelectListItem {Value = "Category2", Text = "attribute3"};

     return Json(new SelectList(listConcatenated, "Value", "Text"));

 }

I would like to find each of the option items in the <select/> list of my view that have the same value as the matching category coming back in my JsonResult, but non-matching Text, and change the "disable" property of each of them to "true."

To reiterate, if I have the following in my current list:

  <select class="Category1Class">
     <option value="Category1">attribute100<option/>
     <option value="Category1">attribute40<option/>
     <option value="Category1">attribute1<option/>
     <option value="Category1">attribute2<option/>
  </select>

Then the jquery function I'm trying to write into the success: result function would return:

  <select class="Category1Class">
     <option value="Category1" disabled>attribute100<option/>
     <option value="Category1" disabled>attribute40<option/>
     <option value="Category1">attribute1<option/>
     <option value="Category1">attribute2<option/>
  </select>                     

I hope this makes sense. Not sure how to begin when comparing against the Json result. Thank you in advance & please let me know if I could be more clear.

1

There are 1 answers

6
charlietfl On BEST ANSWER

Assuming response looks something like:

[
 { "Value": "Category1","Text": "attribute1"},
 { "Value": "Category1","Text": "attribute2"}
]

You can loop through response using each() and use filter() to isolate the matching DOM elements:

var $opts= $('select.Category1Class option');
/* loop over response as "data" */
$.each(data, function( index, item){
   $opts.filter(function(){
       /* return boolean based on matches */
       return $(this).text() === item.Text && this.value === item.Value;
      /* disable resultant collection */
   }).prop('disabled', true);
});