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>
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...
没有下拉ID:
$("#SelectedCountryId").change(function () {
$('option:selected', $(this)).text();
}
The problem could be on this line:
var selectedText2 = $("#SelectedCountryId:selected").text();
It's looking for the item with id of SelectedCountryId
that is selected, where you really want the option that's selected under SelectedCountryId
, so try:
$('#SelectedCountryId option:selected').text()
链接地址: http://www.djcxy.com/p/83066.html