javascript - 在 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);
}
}
})
});
解决方案
我相信您使用错误的 .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");
推荐阅读
- typescript - 量角器:如何处理应用程序重定向到带有警报框的外部登录应用程序
- python - Docker Compose中的PostgreSQL环境变量'没有为数据库设置密码'
- python - Keras 和 NNN 的分配超过系统内存的 10%
- html - 我想设计一个容器,它可以容纳 3 个内联的 div,其中包含父属性
- javascript - 如何调用同一页面上的php函数?
- node.js - 如何解析这个特定的 json
- c# - 更改小数的精度
- python - 将计算量大的函数应用于 dask 数据帧的最有效方法?
- r - 修改 data.table 以仅包含一个变量的唯一值
- r - Shiny 在本地工作,但以奇怪的方式生产失败