kiks73 kiks73 - 5 months ago 87
jQuery Question

Bootstrap validator not working when input field value is set with jQuery .val()

I've got a form with this field:

<form id="formdelivery" class ="form-horizontal form-custom">
<fieldset>
<input name="delivery" type="text" class="" value="">
</fieldset>
</form>


The value of the input field could be copied from another input with a click on a button:

$('#copy').click(function () {
$('[name=delivery]').val($('[name=billing]').val());
var res = $('#formdelivery').data('bootstrapValidator').validate();
if (res.$invalidFields.length == 0) {
alert("ok");
}
else {
alert("no");
}
});


The validation applied on the field is this:

$('#formdelivery').bootstrapValidator({
fields: {
delivery: {
message: 'Invalid',
validators: {
notEmpty: {
},
stringLength: {
min: 2,
max: 100,
message: 'you need almost 2 chars and not more than 100'
}
}
}
});


The problem is that clicking on the copy button, bootstrap validator ignores the new value copied with jQuery code
$('[name=delivery]').val($('[name=billing]').val());


Am I doing something wrong or is this a issue?

Answer

As suggested by Youness, I added the $('[name=delivery]').change(); after updating the input content to validate.

Then I added the trigger line to the bootstrap validator initialization:

$('#formdelivery').bootstrapValidator({
       fields: {
            delivery: {
                trigger: 'change keyup',
                ...

In this way validation is done also on change event.