如何检查PasswordFor是否为空

时间:2017-03-09 17:12:32

标签: javascript c# asp.net-mvc razor

我在Razor中有TextBoxFor和PasswordFor,我想用js检查它们是否都填充了一些数据?

我的代码有效,但仅限于有两个TextBox的情况。如何让它也适用于PasswordFor?

 @Html.TextBoxFor(m => m.Login, new {@class = "form-control", @id="tekst1"})
 @Html.PasswordFor(m => m.Password, new {@class = "form-control", @id="tekst2"})


     <script type="text/javascript">

    function disableButtons() {
        $("input[type='submit']").attr("disabled", true);
    }

    function enableButtons() {
        $("input[type='submit']").attr("disabled", false);
    }

    $(document).ready(function () {
        disableButtons();

        var $textInputs = $('input[type="text"],textInputs');
        $('input').on('change', function () {

            var anyEmpty = $textInputs.filter(function () { return this.value == ""; }).length > 0;
            if (!anyEmpty) {
                enableButtons();
            } else {
                disableButtons();
            }
        });
    });
</script>

1 个答案:

答案 0 :(得分:0)

这个剃刀代码:

@Html.TextBoxFor(m => m.Login, new {@class = "form-control", @id="tekst1"})
@Html.PasswordFor(m => m.Password, new {@class = "form-control", @id="tekst2"})

向浏览器呈现这样的内容:

<input type="text" class="form-control" id="tekst1">
<input type="password" class="form-control" id="tekst2">

(它也可能呈现标签和可能的其他属性,但这些是重要的部分)。

运行以下代码时:

var $textInputs = $('input[type="text"],textInputs');

jQuery寻找以下元素:

<input type="text" (any other attributes)>
<textInputs></textInputs>

如您所见,<input type="password" class="form-control" id="tekst2">与任何一种模式都不匹配。所以,$textInputs中唯一的问题是:

<input type="text" class="form-control" id="tekst1">

如果您在该输入中输入了值,则在过滤器后输入:

$textInputs.filter(function () { return this.value == ""; }).length

将等于0,因此anyEmptyfalseenableButtons将被调用。

如果您要查找空的所有input元素,无论其type属性如何,请将该行更改为:

var $textInputs = $('input');

或者,您可以在单个函数中完成所有这些操作,例如:

$(function() {
  $(':input:not(:button):not(:submit)').on('change', function() {
    $(':submit').prop('disabled', $(':input:not(:button):not(:submit)').filter(function(el) {
      el.value === '';
    }).length > 0);
  });
});

请注意,':input:not(:button):not(:submit)'是一个选择器,它将匹配除按钮之外的所有表单元素,而':submit'仅匹配提交按钮。请参阅jQuery's documentation on form selectors