0

I have a Multi Select List generated by HTML.ListBoxFor. The select element has an id of '#listBox'

I want to add a title attribute to each option tag. The value of the title attribute comes from a Dictionary<string,string>.

I want to do the following

loop through option element of the selectlist and get the text of the option element

loop through each element of Dictionary

Where dictionary.key == text add a title attribute with the value of Dictionary.Value.

MrBliz
  • 5,830
  • 15
  • 57
  • 81
  • I haven't done jQuery for ages, so i'm pretty much stuck at the first hurdle, of even looping through the option elements of the selectlist – MrBliz Jul 11 '12 at 13:55
  • 1
    $('#yourSelect option').each(function(){..do stuff..}); – sirrocco Jul 11 '12 at 14:00
  • 1
    @Doozer1979 You will not be able to do that, since you can't loop on your server-side type after you get text client-side with Jquery,since client-side only works after page is rendered. Is there some other way you can get those values from Option Element? Where do you get text from? – formatc Jul 11 '12 at 14:10
  • The text is the innerHtml of the option element – MrBliz Jul 11 '12 at 14:16
  • I guess i'll have to get the values into an regular javascript array – MrBliz Jul 11 '12 at 14:16
  • @Doozer1979 Exactly what I was going to suggest, take a look at this [Jquery Dictionary](http://stackoverflow.com/questions/5402180/does-jquery-support-dictionaries-key-value-collection) – formatc Jul 11 '12 at 14:18
  • You could always use ajax to return a json encoed array of your dictionary items, and then parse those in the `success: function(data)`, it will allow you to manipulate the elements before being inserted into the DOM, unlike what @user101609 said. – Ohgodwhy Jul 11 '12 at 14:38
  • @Ohgodwhy Yes that is correct, but why would you want do this if you already have your items in the View? – formatc Jul 11 '12 at 14:53
  • how are you sending the list to the view ? could you show your code for your ViewPage and the controller action that returns the view? Also why do u need to set a title attribute? the reason i ask is you could extend the DorpDownListFor helper method and do this server side. look [here](http://stackoverflow.com/q/7536631/1279541) – keshav Jul 11 '12 at 16:33

1 Answers1

0

Check out this post Add attribute to select list option. It allows you to put any attributes you want into the option items of a dropdown.

Community
  • 1
  • 1
nikeaa
  • 1,047
  • 7
  • 17