Reputation: 73
I have been scratching my head for hours trying to solve this problem. I have tried most codes out there regarding this question and have not succeeded in getting a proper guide and answer to working with @html.dropdown. I have a dropdown which gets value from controller ViewBag.
public ActionResult FindBirthStones()
{
ViewBag.birthstones = new SelectList(dbcontext.GemStoneByMonths, "GemStoneByMonthId", "EnglishZodiac");
return View();
}
and in my View I have written.
@Html.DropDownListFor(m=>m.EnglishZodiac,(SelectList)ViewBag.birthstones, new { @id = "hello" })
I have tried @html.dropdownlist instead of listfor.
@Html.DropDownList("EnglishZodiac", (SelectList)ViewBag.birthstones, new { @id = "hello" })
and I want to get the selected value from the dropdownlist or listfor using jquery. I have tried most answers which are
var a= $("hello").text()
var a= $("hello option:selected").text()
var a= $("hello :selected").text()
and none of them work. Can someone please help me with it.
Upvotes: 0
Views: 616
Reputation: 62311
Ideally, you do not need to rename DropDownList
's id to hello
.
@Html.DropDownListFor(m => m.EnglishZodiac, (SelectList)ViewBag.birthstones));
Instead, you need to use #
to get an element by ID inside jQuery. How do I get the text value of a selected option?
var a = $("#EnglishZodiac option:selected").text();
If the script is inside View.cshtml
, you could even use strongly-typed html helper Html.IdFor
.
$("#@Html.IdFor(m => m.EnglishZodiac) option:selected").text();
If you want to get the selected value, you could just use .val()
.
var a = $("#EnglishZodiac").val();
Upvotes: 1
Reputation: 3413
To reference an element by it's id you need to use the hash (#) selector, like this:
// To get the text of the selected option
var a = $("#hello option:selected").text();
// To get the value of the selected option
var b = $("#hello").val();
Upvotes: 1