2017-03-09 113 views
-4

我在Razor TextBoxFor和PasswordFor,我想检查使用js,如果他们都充满了一些数据?如何检查是否PasswordFor为空

我的代码工作,但只有在有两个文本框的情况下。如何使它适用于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> 
+0

请向我们展示所有相关代码(并正确格式化)。 – domsson

+0

这不是纯粹的_html_。请修改您的标签。 – Optio

+0

没有'textbox'这样的元素,所以你可以从你的选择器中删除它。然后,将'$ textInputs'的选择器更改为'$('input')'。密码字段上有'type =“password”',显然'type =“text”'不匹配。 –

回答

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

+0

您应该开始学习ASP.NET MVC的标签助手发出的内容,以及jQuery(和CSS)选择器如何工作。相信我,从长远看付出代价。 –

+0

它的工作原理。非常感谢 – Karolina