Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery to get SelectedText from dropdown

I am trying to get the selected Text from the dropdownlist using Jquery.

<div>     @Html.DropDownList("SelectedCountryId", Model.CountryList, "(Select one Country)") </div> 

Given below is the Jquery that I am using. But this is not working. I tried

var selectedText1 = $("#SelectedCountryId").val($(this).find(":selected").text());  

and is returning [object object]. But how to read the selected text?

Next I tried

var selectedText2 = $("#SelectedCountryId:selected").text(); 

Then it's returning empty.

I also tried

var selectedText2 = $("#SelectedCountryId option:selected").text(); 

This also returned empty.

I am able to return the selectedID using

var selectedID = $("#SelectedCountryId").val(); 

But why not the selected text?

Is there anything wrong with my Jquery here? Please help

<script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>     <script type="text/javascript">         $(document).ready(function () {             $("#SelectedCountryId").change(function () {                  var selectedText1 = $("#SelectedCountryId").val($(this).find(":selected").text());                 var selectedText2 = $("#SelectedCountryId:selected").text();                 alert("You selected :" + selectedText1 + selectedText2 );               }); 

This is the HTML for my dropdown below

<select id="SelectedCountryId" name="SelectedCountryId"><option value="">(Select one Country)</option> <option value="19">USA</option> <option value="10">Germany</option> <option value="12">Australia</option> </select> 
like image 806
Millar Avatar asked Apr 23 '12 23:04

Millar


People also ask

How do I get text from a dropdown list?

Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How do I select a specific DropDownList using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How get dropdown value in jQuery in MVC?

Use $("#ctrlName"). val() to get selected value and $("#ctrlName option:selected").


2 Answers

I had the same problem yesterday :-)

$("#SelectedCountryId option:selected").text() 

I also read that this is slow, if you want to use it often you should probably use something else.

I don't know why yours is not working, this one is for me, maybe someone else can help...

like image 125
Philipp Avatar answered Sep 21 '22 17:09

Philipp


Without dropdown ID:

$("#SelectedCountryId").change(function () {     $('option:selected', $(this)).text(); } 
like image 30
MCurbelo Avatar answered Sep 24 '22 17:09

MCurbelo