Search code examples
jqueryvalidationtwitter-bootstrap-3bootstrapvalidatorjqbootstrapvalidation

Bootstrap Validator still shows error message after setting value through jquery


I'm changing a value of a drop-down 01 based on another drop-down 02 via jquery change(). And i have implemented BootsrapValidation() to the form. My issue is if required field error message is displayed for the dropdown 01 and then i set dropdown 01 value from jquery. Yet the error message is still there.

I added $('#form1').bootstrapValidator(); to the end of change() yet no luck. any ideas really appreciated.

Check the fiddle from here: https://jsfiddle.net/k2vtkka1/5/

here is my code.

$(document).ready(function() {


$('.subSort').change(function(){;
    var sub_code = $(this).val();
    var code_id = $(this).attr("id");

    var code_prefix = sub_code.substring(0, 4);
    var id_prefix = code_id.substring(4, 5);

    var new_sub_code = code_prefix+'102';
    var new_id_no = parseInt(id_prefix)+1;

    $('#sub_'+new_id_no).val(new_sub_code);
    $('#update_student_form').bootstrapValidator();
});


$('#update_student_form').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: { 
            sub_6: {
            validators: {
                notEmpty: {
                    message: 'Please select main sub 01 derived'
                }
               }
            }
        }
    })


    .on('success.form.bv', function(e) {
            $('#update_student_form').data('bootstrapValidator').resetForm();

        e.preventDefault();

        var $form = $(e.target);
        var bv = $form.data('bootstrapValidator');

        // Use Ajax to submit form data
        $.post($form.attr('action'), $form.serialize()).done(function(data) {
            if (data.trim().length >0)
            {
                $('#error_message').slideDown({ opacity: "show" }, "slow");
            }
            else {
                $('#success_message').slideDown({ opacity: "show" }, "slow");
            }
        });
});

Solution

  • Finally I found the problem:-

    Actually the code:-

    $('#sub_'+new_id_no).val(new_sub_code);
    

    Is not changing the value in second select-box (although it's showing that value changed).That's why it's not proceeding further, after error came there.

    You need to trigger change() there so that it actually change the value and then your validator get it.

    So change the above line with this:-

    $('#sub_'+new_id_no).val(new_sub_code).change();
    

    Working example:-https://jsfiddle.net/fn0r4nvh/

    Reference:- change()