How to dynamically disable TextBox in MVC Razor?

2019-05-26 19:09发布

I want to dynamically disable/enable textbox aftre clicking the checkbox. How can I do it? I'm using this:

@{
    object addInput = (Model.AddInput) ? null : new { disabled = "disabled" };

 }

@Html.CheckBoxFor(model=> model.AddInput)

@Html.TextBoxFor(model => model.Input.Name, addInput)

but it works only on start. Clicking the checkbox isn't changing anything. How can do some binding to change disable state automaticaly?

3条回答
姐就是有狂的资本
2楼-- · 2019-05-26 19:38

This needs to be done in javascript.

@{
    object addInput = (Model.AddInput) ? null : new { disabled = "disabled" };

 }

@Html.CheckBoxFor(model=> model.AddInput)

@Html.TextBoxFor(model => model.Input.Name)


<script> 
    $('#AddInput').click(function() {
        var $this = $(this);

        if ($this.is(':checked')) {
            $('#Name').removeAttr("disabled"); 
        } else {
            $('#Name').attr("disabled", "disabled")
        }
    });
</script>
查看更多
一夜七次
3楼-- · 2019-05-26 19:48

Add jquery action on click on your checkbox and set state appropriately.

查看更多
Evening l夕情丶
4楼-- · 2019-05-26 19:58

In case you want to enable it for some reason, you can also use the following:

      $('#Name').attr("disabled", false);
查看更多
登录 后发表回答