我有一个带有动态输入字段数的表单:用户可以添加新项目,完成后他可以发送表单。表单使用 FormValidation (formValidation.io) 在发送前检查内容,以便更轻松地填写所有正确的数据。
问题是:只有第一个字段(加载页面时已经存在的那个)被检查,所有其他字段都被 FormValidation 跳过。
添加新字段时,我尝试再次调用 FormValidation,但这没有区别。我尝试仅在添加新字段时调用 FormValidation,并且它仅在第一次工作,包括前两个字段但跳过以后添加的任何字段。看起来 FormValidation 只能调用一次,并且只考虑当时存在的内容。
每次添加新字段时,您能否设计一种让 FormValidation 为整个表单工作的方法?
这是添加新输入字段的代码:
<script>
// add input filed to form
$(document).ready(function () {
//when the AddBox button is clicked
$(".add").click(function (e) {
var randomnumber=Math.floor(Math.random()*999999);
//Append a new row of code to the "#items" div
var newrow='';
newrow+='<div class="item">';
newrow+='<div class="form-group">';
newrow+='<button type="button" class="btn btn-default delete" >remove</button> ';
newrow+='<label class="sr-only" for="boxname">boxname</label>';
newrow+='<input type="text" class="form-control" id="boxname_'+randomnumber+'" name="boxname[]" placeholder="boxname"';
newrow+=' data-fv-notempty="true"';
newrow+=' data-fv-notempty-message="The boxname is required"';
newrow+=' >';
newrow+='</div> ';
newrow+='</div>';
$("#items").append(newrow);
$("#formbox").formValidation(); // call formvalidation again but field is not checked
});
//when the remove button is clicked
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
})
// call formvalidation
$(document).ready(function() {
$('#formbox').formValidation();
});
</script>
这是html:
<form
id="formbox"
class="form-inline"
action="index.php"
method="post"
data-fv-framework="bootstrap"
data-fv-icon-valid="glyphicon glyphicon-ok"
data-fv-icon-invalid="glyphicon glyphicon-remove"
data-fv-icon-validating="glyphicon glyphicon-refresh"
data-fv-err-container="tooltip"
>
<div id="items">
<div class="item">
<div class="form-group">
<button type="button" class="btn btn-default delete" >remove</button>
<label class="sr-only" for="boxname">boxname</label>
<input type="text" class="form-control" id="boxname_1" name="boxname[]" placeholder="box 1" value="box 1"
data-fv-notempty="true"
data-fv-notempty-message="The boxname is required"
>
</div>
</div>
</div>
<br>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default add">add box</button>
<button type="submit" class="btn btn-default">send</button>
</div>
</form>