javascript - MVC : Get selected text from <Select> using JQuery

标签 javascript jquery html asp.net-mvc-4

我正在尝试从下拉列表中获取所选项目并将其用于验证。

以前我用过:

$("#PolicyOrganisation").text());

这有效,但后来我将下拉菜单更改为以下内容(从数据库加载而不是硬编码):

<div class="form-group">
    <label for="diagnosticMode" class="control-label col-xs-2">Policy Organisation:</label>
    <select id="DD1" name="PolicyOrganisation">
        <option value="-1">Select</option>
        @foreach (var item in ViewBag.PolicyOrgs)
        {
            <option value="@item.Id">@item.Name</option>
        }
    </select>
</div>

还有我的 JQuery 验证:

 //Validation for Dropdown      
    var platform1 = $('#PolicyOrganisation option:selected').text();
    var Valid1 = (platform1 !== 'Select')
    if (!Valid1) {
        $('#PolicyOrganisation').css({
            "border": "1px solid red",
            "background": "#FFCECE"
        });
    }

我通过搜索这个问题找到了这个方法.. Get selected text from a drop-down list (select box) using jQuery

但是新版本不起作用?谁能解释一下为什么会这样?

最佳答案

“PolicyOrganization”不是 ID,而是名称属性请使用“DD1”而不是“PolicyOrganization”

var platform1 = $('#DD1 option:selected').text();
    var Valid1 = (platform1 !== 'Select')
    if (!Valid1) {
        $('#DD1').css({
            "border": "1px solid red",
            "background": "#FFCECE"
        });
    }

关于javascript - MVC : Get selected text from <Select> using JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25930389/

相关文章:

html - 两条边倾斜度不同的 Div

php - 如何在 <head> 标签内使用 PHP 添加 css 文件?

javascript - 找不到 babel.config.json 中指定的模块

javascript - jQuery:检查具有特定类名的 div 是否存在

javascript - 将 IF 语句与 OR 一起使用的更好方法

javascript - 设置文件上传字段值 - Javascript/jQuery

javascript - 使用 JQuery 打开关闭菜单

javascript - 允许在值绑定(bind) react 输入中使用减号(-)

javascript - 从 jquery UI 可调整大小的元素中删除句柄图像

javascript - Angular : Using "this" instead of "$scope" in "Controller As"