4

On MVC3, with a dropdownlist defined as

@Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"))

How can I get the selected value and/or text via javascript?

I tried passing a name:

  @Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"), new {name="name")

and reading the name from the javascript: document.getElementByName("name")

but that does not work.

jpo
  • 3,959
  • 20
  • 59
  • 102

1 Answers1

4

If you are using jQuery (which is highly likely with an MVC project):

// lambda to get the ID of your dropdown. This runs on the server,
// and injects the ID into a client-side variable.
var id = '@Html.IdFor( o => o.model )';

// get the dropdown by ID and wrap in a jQuery object for easy manipulation
var dropdown = $("#" + id);

// get the value
var value = dropdown.val();

Of course, you could combine this into a single line if desired.

If you aren't using jQuery, see https://stackoverflow.com/a/1085810/453277.

var id = '@Html.IdFor( o => o.model )';
var dropdown = document.getElementById( id );
var value = dropdown.options[dropdown.selectedIndex].value;

Manual ID:

@Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"), new {id = "ddl1"})

var value = $("#ddl1").val();
Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
  • I have a couple of dropdownmenu on my view. How will I differentiate between them in the script? – jpo Dec 12 '12 at 15:00
  • You should use an ID to differentiate. Usually you can automatically obtain this from `Html.IdFor()` but you can also manually add an ID. I'll add an example. – Tim M. Dec 12 '12 at 15:02
  • Thanks alot. That worked. To get the selected value, i did var value = $("#ddl1 option:selected").val(); – jpo Dec 12 '12 at 15:14
  • 1
    Just var value = $("#ddl1").val() will get the currently selected item. No need to add option:selected. – IyaTaisho Dec 12 '12 at 15:53