我正在使用这个 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/