[英]jquery - get selected dropdown value on document ready
我想遍歷頁面並找到具有特定ID的每個下拉菜單。 在頁面首次加載時,訪問下拉菜單的選項集合沒有問題,但沒有默認的選擇值。
我有這個下拉列表處於循環中:
@Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"), new {id = "ddlInterviewer" })
這是我的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);
}
});
我想為頁面上的每個下拉菜單項添加一個類。 addClass用於以其他顏色樣式化下拉菜單項。
在我的屏幕截圖中,只有未選中的項目才會有顏色。 那是因為javascript添加了類。 我想向頁面加載時默認選擇的值添加一個類。
您可以使用: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");
}
}
});
您也可以直接定位選定的
$("#InterviewManagementFrm #ddlInterviewer > option:selected")
如果#ddlInterviewer
是選擇的ID,則您不需要>
ID也應該是唯一的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.