I have a form with dynamic number of input fields: the user can add new items and when he's finished he can send the form. The form uses FormValidation (formValidation.io) to check content before sending, to make it easier to fill in all the right data.
The problem is: only the first field (the one already existing when the page is loaded) get checked, all the others are skipped by FormValidation.
I tried calling FormValidation again when adding a new field, but it makes no difference. I tried calling FormValidation only when adding a new field, and it works only the first time, including the first two fields but skipping any field added later. It looks as if FormValidation can be called only once, and takes in consideration only what is present at that time.
Can you devise a way to have FormValidation working for the whole form each time a new field is added?
This is the code to add new input fields:
<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>
This is the 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>