jquery - 在文档就绪时获取选定的下拉值

时间:2014-05-28 14:38:35

标签: javascript jquery drop-down-menu

我想遍历我的页面,找到具有特定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用于使用不同的颜色设置下拉项的样式。

enter image description here

在我的屏幕截图中,只有未选择的项目有颜色。这是因为javascript添加了类。我想在页面加载时默认选择的值中添加一个类。

1 个答案:

答案 0 :(得分:1)

您可以使用: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也应该是唯一的

相关问题