首页 > 解决方案 > 在 jquery 中设置原始下拉文本

问题描述

我正在尝试从下拉列表中选择不同的值,并根据下拉列表中新选择的文本检查逻辑,并比较在文本框中输入的文本。如果选定的下拉文本和文本框值不符合逻辑,我想恢复到以前在下拉框中显示的原始文本。

例如:在我的下拉框中,我的值为“有效”、“无效”、“PCR IN”、“PCR OUT”,并且下拉列表已经显示“有效”。如果用户将值从“有效”更改为“PCR IN”并且第二个文本框值如果更改为负数,我会通过引导框向用户抛出错误,说文本框值应该是正数。

但是我需要在用户更改为“PCR IN”之前将原始值更改为下拉菜单中显示的“有效”。我的代码没有按预期运行。它在下拉列表中放置一个空结果[附加]空值

我的代码如下:用于创建下拉模型的我的 MVC 视图页面:

 @Html.DropDownListFor(model => model.FundingStatusId, new SelectList(ViewBag.FundingStatusDdl, "FundingStatusId", "FundingStatusName"), "Select Fund Status", htmlAttributes: new { @class = "form-control rtscustomtextboxright", @id = "fundingstatus" })

$(function () {
        var fundingStat = $("#fundingstatus option:selected").text();
       
        $("#fundingstatus").change(function () {
            if ($("#fundingstatus option:selected").text() == 'PCR IN') {
                //  debugger
                if (parseFloat($('#additionalFunds').val(), 10) > 0) {
                    bootbox.alert({
                        title: "ERROR - Please fix this",
                        size: "lg",
                        message: "<br><br><br>Additional Funds must be a NEGATIVE $ amount"
                    })
                   // return false;
                    $("#fundingstatus").val(fundingStat);
                }
            }
        })
    });

标签: javascriptjquery

解决方案


我相信您使用错误的 .val() 方法。

var fundingStat = $("#fundingstatus option:selected").text();
$("#fundingstatus").val(fundingStat); // you set the val for the option's text and not its value.

您没有在问题中提及下拉列表的代码,因此我无法编写修复程序,但请查看以下说明:

如果我们有以下下拉列表:

<div class="test">
  <select>
    <option value="a">First Choice</option>
    <option value="b">Second Choice</option>
    <option value="c">Third Choice</option>
  </select>
</div>

为了设置选定的选项,我们应该使用带有的 .val()而不是text()

$(".text select").val("b"); // will select the "Second Choice"

而不是

$(".text select").val("Second Choice");

推荐阅读