[英]jquery - get selected dropdown value on document ready
I want to loop through my page and find every dropdown menu with a specific ID. 我想遍历页面并找到具有特定ID的每个下拉菜单。 I have no problem accessing the options collection of a dropdown but not the default selected value when the page first loads. 在页面首次加载时,访问下拉菜单的选项集合没有问题,但没有默认的选择值。
I have this dropdown which is in a loop: 我有这个下拉列表处于循环中:
@Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"), new {id = "ddlInterviewer" })
Here is my js which is in an external script: 这是我的js,位于外部脚本中:
$("#InterviewManagementFrm #ddlInterviewer > option").each(function () {
var lastChar = this.text.substr(this.text.length - 1);
if (lastChar == 'A') {
$(this).addClass("AcceptedPreference");
// this.text = this.text.slice(0, this.text.length - 1);
}
else if (lastChar == 'P') {
$(this).addClass("PreferredPreference");
// this.text = this.text.slice(0, this.text.length - 1);
}
});
I want to add a class to every dropdown item on the page. 我想为页面上的每个下拉菜单项添加一个类。 The addClass is used to stylize the dropdown item with a different color. addClass用于以其他颜色样式化下拉菜单项。
In my screenshot only unselected items have a color. 在我的屏幕截图中,只有未选中的项目才会有颜色。 That's because of the javascript adding the class. 那是因为javascript添加了类。 I want to add a class to the values that are selected by default on page load. 我想向页面加载时默认选择的值添加一个类。
You can use the :selected
http://api.jquery.com/selected-selector/ 您可以使用:selected
http://api.jquery.com/selected-selector/
$("#InterviewManagementFrm #ddlInterviewer > option").each(function () {
var lastChar = this.text.substr(this.text.length - 1);
if (lastChar == 'A') {
if( $(this).is(':selected') ) {
// add class
} else {
$(this).addClass("AcceptedPreference");
}
}
else if (lastChar == 'P') {
if( $(this).is(':selected') ) {
// add class
} else {
$(this).addClass("PreferredPreference");
}
}
});
You can also directly target the selected 您也可以直接定位选定的
$("#InterviewManagementFrm #ddlInterviewer > option:selected")
if #ddlInterviewer
is the id of the select then you don't need >
also ID should be unique 如果#ddlInterviewer
是选择的ID,则您不需要>
ID也应该是唯一的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.