在Razor视图中启用/禁用客户端上的字段

时间:2017-09-12 19:24:36

标签: javascript asp.net-mvc razor

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

<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。当我尝试单步执行代码时,它会在页面最初加载时停止,但每次单击复选框时都不会运行。

1 个答案:

答案 0 :(得分:0)

click事件之前放置ready方法处理块按预期工作,无需在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>

注意:请记住在head元素中包含jQuery脚本文件,或者通过script元素(<script src="[path_to_jquery_script].js">)或使用System.Web.Optimization script bundling

工作示例:.NET Fiddle Demo