【问题标题】:Validation for element in a loop验证循环中的元素
【发布时间】:2019-04-29 03:48:51
【问题描述】:

我在验证 for 循环中的每个 PhoneNumber 文本框时遇到问题。 我的验证功能适用于单个 Texbox,但是当我尝试应用于循环时,我不知道 javascript 如何理解循环的索引。

需要帮助!

@for (int i = 0; i < Model.Count; i++)
  {
    <tr>
       <td>
         <div>
            <b>Phone Number:</b>
             @Html.EditorFor(model => model[i].Hotline, new { htmlAttributes = new { @class = "form-control ShortInput", id = "hotline[i]//html doesn't understand the index here"  maxlength = "15" } })
             <span class="ErrorBlock field-validation-valid"></span>
          </div>
         </td>
</tr>

这是验证函数:

function validateForm() {
     var result = true;
     result = checkPhone('#hotLine//"how could I get the index here"', 'Invalid phone number.') && result;
      return result;
        }

【问题讨论】:

  • 嗯,你要做的是首先获取所有元素,你可以通过使用 css 类并在 jquery 中从类名中搜索元素来获取这些元素,在你获取所有元素之后,你可以使用 foreach 获取所有元素一一验证

标签: javascript c# html


【解决方案1】:

它无法识别 html 中的索引,因为它把它当作一个字符串。您可以做的是,在循环内,使用 var,然后将该 var 分配给您的 id。 比如:

@for (int i = 0; i < Model.Count; i++)
  {
    var dynamicId = "hotline["+@i+"]";
    <tr>
       <td>
         <div>
            <b>Phone Number:</b>
             @Html.EditorFor(model => model[i].Hotline, new { htmlAttributes = new { @class = "form-control ShortInput", id = dynamicId  maxlength = "15" } })
             <span class="ErrorBlock field-validation-valid"></span>
          </div>
         </td>
</tr>

可能有一些语法错误,但这应该可以。

在jquery中,你可以做这样的事情;

function validateForm() {
     var result = true;
     $('.ShortInput').each(function() {
    var id = $(this).id; 
    // TODO: whatever operation you want to perform
});
        }

【讨论】:

  • 这就是为什么我评论你应该做这样的事情。我不知道您想要预先并运行确切的代码。你可以通过一些小的改动来尝试这个,它会奏效的:)
猜你喜欢
  • 2014-05-22
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
相关资源
最近更新 更多