如问题所述,如何使用jQuery设置DropDownList控件的值?
$("#mydropdownlist").val("thevalue");
只需确保选项标签中的值与val方法中的值匹配即可。
如@Nick Berardi所建议,如果您修改的值没有在UI前端反映出来,请尝试:
$("#mydropdownlist").val("thevalue").change();
selectmenu
未定义,但change()
可以解决问题。 - Chad Hedgcock如果你正在使用索引,你可以使用 .attr() 直接设置所选索引:
$("#mydropdownlist").attr('selectedIndex', 0);
这将把它设置为下拉列表中的第一个值。
编辑: 我之前的做法曾经有效。但现在似乎不再起作用了。
但正如Han在评论中所指出的那样,正确的做法是:
$("#mydropdownlist").get(0).selectedIndex = index_here;
select
标签没有名为 selectedIndex
的属性,这是 DOM 对象的属性。因此代码应该是:$("#mydropdownlist").get(0).selectedIndex = index_here;
- Han$("#mydropdownlist").prop('selectedIndex', index_here);
可以正常工作。 翻译描述:这是一行JavaScript代码,用于将下拉列表中的选定索引更改为给定的 index_here
值。 - numaroth$("#mydropdownlist").get(0).selectedIndex = index_here;
在 jQuery 3.3.1 中是可行的。 - Prasad尝试这个非常简单的方法:
/*make sure that value is included in the options value of the dropdownlist
e.g.
(<select><option value='CA'>California</option><option value='AK'>Alaska</option> </select>)
*/
$('#mycontrolId').val(myvalue).attr("selected", "selected");
$("#mycontrolId").selectmenu('refresh');
。 - VladL$('#mycontrolId').selectmenu('refresh').val(myvalue).attr("selected", "selected");
吗? - Dylan Czenski $("#<%=DropDownName.ClientID%>")[0].selectedIndex=0;
$("#DropDownName")[0].selectedIndex=0;
该问题的最佳答案:
$("#comboboxid").val(yourvalue).trigger("chosen:updated");
e.g:
$("#CityID").val(20).trigger("chosen:updated");
或者
$("#CityID").val("chicago").trigger("chosen:updated");
$("._statusDDL").val('2');
或者
$('select').prop('selectedIndex', 3);
设置值并更新下拉列表事件
$("#id").val("1234").change();
如果你只需要设置下拉选项的值,最好的方法是:
$("#ID").val("2");
如果您需要在更新下拉列表值后触发任何脚本,比如如果您在下拉列表上设置了任何onChange事件并且希望在更新下拉列表后运行此事件,则需要使用以下方法:
$("#ID").val("2").change();
$.getJSON('<%= Url.Action("GetDepartment") %>',
{ coDepartment: paramDepartment },
function(data) {
$(".autoCompleteDepartment").empty();
$(".autoCompleteDepartment").append($("<option />").val(-1));
$.each(data, function() {
$(".autoCompleteDepartment").append($("<option />").val(this.CodDepartment).text(this.DepartmentName));
});
$(".autoCompleteDepartment").val(-1);
}
);
$("#mycontrolId").selectmenu('refresh');
来反映更改。 - VladL