javascript - 在for循环中生成html

标签 javascript jquery html css

我正在使用这个 jquery 验证:http://www.runningcoder.org/jqueryvalidation/

它工作得很好,但如果我用 javascript 动态生成我的代码,如果输入之一未能通过数据验证,则错误消息将出现在所有输入中。

有办法解决这个问题吗?

for (var i = 0; i < result.length; i++) {
  inputs += '<div class="input-group bottom15"><span class="input-group-addon">' + (i + 1) + '</span>' +
    '<input type="text" class="form-control" placeholder="Insert the description for ' + result[i] + '"  name="paramDescriptions" id="paramName' + (i + 1) + '"' +
    'data-validation-message="The description must be between 2 and 25 characters. No special characters allowed."\n' +
    'data-validation="[L>=2, L<=25, MIXED]" required></div>';
}

上面的代码生成...

<div id="inputDiv" class="col-sm-10">
  <div class="input-group bottom15"><span class="input-group-addon">1</span><input type="text" class="form-control" placeholder="Insert the description for FREQUENCY" name="paramDescriptions" id="paramName1" data-validation-message="The description must be between 2 and 25 characters. No special characters allowed."
      data-validation="[L>=2, L<=25, MIXED]" required=""></div>
  <div class="input-group bottom15"><span class="input-group-addon">2</span><input type="hidden" class="form-control" name="paramName" value="DAYS"><input type="text" class="form-control" placeholder="Insert the description for DAYS" name="paramDescriptions" id="paramName2" data-validation-message="The description must be between 2 and 25 characters. No special characters allowed."
      data-validation="[L>=2, L<=25, MIXED]" required=""></div>
</div>

最佳答案

jQuery form Validation使用这部分代码查找元素:

node.find('input:not([type="submit"]), select, textarea')

因此,您示例中的每个 input 字段都将被检查。但是,错误是针对字段的名称属性注册的:

var inputName = $(input).attr('name')

// ...

registerError(inputName, error[0].replace('$', inputShortName).replace('%', error[1]));

这就是您看到两个字段的错误消息的原因。

只需将字段的名称值更改为唯一值即可解决此问题。

关于javascript - 在for循环中生成html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193257/

相关文章:

javascript - 对 C# Controller 方法进行 Ajax 调用

javascript - 在 Ajax 中发送复选框 True 或 False

javascript - 如何将 "fill_parent"值设置为元素的宽度?

javascript - 如何在jsPlumb中获取连接数据

javascript - 单选按钮启用/更改提交按钮上的 CSS

javascript - 如何减少 GridStack 网格元素的最小高度和重量?

javascript - 从嵌套 div 结构预填充表单 : front-end design advice

jquery - 通过 jQuery 更改源后 html 音频找不到文件

c# - 如何在按赞按钮后获取用户信息

javascript - 如何在 UIWebview 中将 XCode 变量传递给本地 HTML