简体   繁体   English

如何通过 JavaScript/JQuery 更改选定的 DropDownList 项目?

[英]How to change selected DropDownList item via JavaScript/JQuery?

I want to change the selected option of my ASP.NET DropDownList using JS / JQuery and get the selected Value later on.我想使用 JS / JQuery 更改我的 ASP.NET DropDownList 的选定选项,然后稍后获取选定的值。

In DOM:在 DOM 中:

<select id="myDDL" name="myDDL">
  <option selected="selected" value="0"> Option 1 </option>
  <option value="1"> Option 2 </option>
  <option value="2"> Option 3 </option>
</select>

I tried $("#myDDL").val(1);我试过$("#myDDL").val(1); but this does not work 100%.但这不是 100% 有效的。 The text of it will be displayed ("Option 2") but there is still the first option selected in DOM.它的文本将被显示(“选项 2”),但在 DOM 中仍然选择了第一个选项。

I want to get the selectedValue in a code behind button onclick method using我想在按钮 onclick 方法后面的代码中使用 selectedValue

protected void myButton_Click(object sender, EventArgs e)
{
  int val = myDDL.SelectedValue;
  ...
}

but this returns 0 instead of 1, which means Option 1 is still selected.但这会返回 0 而不是 1,这意味着仍然选择了选项 1。

So what do I have to do to set the second option correctly?那么我该怎么做才能正确设置第二个选项? And why does the displayed text change to the one of option 2, but not the selected attribut?为什么显示的文本更改为选项 2 之一,而不是选定的属性?

Cheers干杯

You can use the selectedIndex , like so:您可以使用selectedIndex ,如下所示:

 let select = document.getElementById("myDDL"); select.options.selectedIndex = 1;
 <select id="myDDL" name="myDDL"> <option selected="selected" value="0"> Option 1 </option> <option value="1"> Option 2 </option> <option value="2"> Option 3 </option> </select>

The HTMLSelectElement.selectedIndex is a long that reflects the index of the first or last selected element, depending on the value of multiple. HTMLSelectElement.selectedIndex 是一个 long 值,它反映了第一个或最后一个选定元素的索引,具体取决于 multiple 的值。 The value -1 indicates that no element is selected.值 -1 表示未选择任何元素。

 $('#myDDL').change(function() { val= $('#myDDL:selected').map(function(i, el) { return $(el).val(); }).get(); console.log(val); });

I figured it out.我想到了。

The problem was that the ViewState of the DropDownList was disabled.问题是 DropDownList 的 ViewState 被禁用。

Adding添加

myDDL.EnableViewState = true;

fixed the problem.解决了这个问题。

Now, using现在,使用

$("#myDDL").val(1);

works fine.工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM