【问题标题】:Enable / Disable Fields on Client Side in Razor view在 Razor 视图中启用/禁用客户端的字段
【发布时间】:2018-02-21 08:43:34
【问题描述】:

我正在尝试添加代码,以便当用户选中某个框时,启用某个字段而禁用另一个字段,如果未选中该复选框,反之亦然。我在这里查看并找到了这段代码:

<head>
<script type="text/javascript">

    $('#UseForecast').click(function() {
        var $this = $(this);

        if ($this.is(':checked')) {
            $('#MinimumOnHandQuantity').removeAttr("disabled");
            $('#ForecastMultiplier').attr("disabled", "disabled")
        } else {
            $('#MinimumOnHandQuantity').attr("disabled", "disabled")
            $('#ForecastMultiplier').removeAttr("disabled");
        }
    });
</script>

</head>

@Html.EditorFor(model => model.UseForecast, new { htmlAttributes = new { @class = "form-control" } })

@Html.EditorFor(model => model.MinimumOnHandQuantity, new { htmlAttributes = new { @class = "form-control" } })

@Html.EditorFor(model => model.ForecastMultiplier, new { htmlAttributes = new { @class = "form-control" } })

我错过了什么?

我对其进行了修改以在我的页面上包含字段的 ID。 UseForecast 是复选框的 id,MinimumOnHandQuantity 是第一个文本框,ForecastMultiplier 是第二个文本框的 id。当我尝试单步执行代码时,它会在页面最初加载时停止,但只要我单击复选框,它就不会运行。

【问题讨论】:

  • 您需要一个文档加载处理程序或将脚本移动到 html 元素下方。还要仔细检查 id 属性以确保帮助程序按照您的预期呈现 id。
  • 你确定 UseForecast 是CheckBox
  • @Jasen,下面在哪里?在页面底部?
  • @Jasen 我把它放在页面底部,它仍然什么都不做,但现在页面最初加载时它崩溃了
  • @AT-2017,我只是再次检查了一个检查元素,它说 type="checkbox"

标签: javascript asp.net-mvc razor


【解决方案1】:

ready 方法处理块放在click 事件之前按预期工作,无需将脚本标签移到head 元素之外:

<head>
<script>
    // this ready method should be added before handling all jQuery DOM event handlers
    $(document).ready(function () {

        $('#UseForecast').click(function() {
            var $this = $(this).is(':checked');

            if ($this) {
                $('#MinimumOnHandQuantity').removeAttr("disabled");
                $('#ForecastMultiplier').attr("disabled", "disabled")
            } else {
                $('#MinimumOnHandQuantity').attr("disabled", "disabled")
                $('#ForecastMultiplier').removeAttr("disabled");
            }
        });
    });
</script>
</head>

注意:请记住通过script 元素(&lt;script src="[path_to_jquery_script].js"&gt;)或使用System.Web.Optimizationscript bundlinghead 元素中包含jQuery 脚本文件。

工作示例:.NET Fiddle Demo

【讨论】:

  • Tetsuya,太棒了,它现在可以工作了。只是好奇,虽然它现在不能在页面加载时运行。我需要它在页面加载和文档准备期间运行。我该怎么做?
  • 你能解释一下“在页面加载期间运行”的意思(禁用默认状态下的文本框之一或其他)吗?我认为您可以添加 jQuery load 方法来处理第一次加载期间的复选框切换。
  • 是的,根据页面加载时数据库中保存的内容禁用一个 - 所以默认值总是不同的。目前我使用 C# 代码执行此操作,但我觉得这是多余的。
猜你喜欢
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多