2

Am using a form where I use the Chosen jQuery for a select tag with 'multiselect' enabled, The options for this select tag are generated from the response of an Ajax call. Along with this select tag there is one textarea field and another select tag with 'single' select (also populated through another Ajax call and not Chosen enabled).

I have also used the bootstrapValidator to validate this form. The issue am facing is that the textarea and the single select are validated but the chosen multiselect is not getting validated. The multiselect is populated through the Ajax response and Chosen is also getting applied on it, but its not getting validated on submit.

HTML

<form role="form" id="createQueForm" enctype="multipart/form-data" novalidate>
    <div class="control-group form-group">
         <label class="control-label">Question Text</label>
         <textarea name="questionText" class="form-control" name="question" rows="3" ></textarea>
    </div>

    <div class="control-group form-group">
        <label class="control-label">Select Tags (upto 3)</label>
        <select multiple class="form-control" id="tags_select" name="tags" >
        </select>
    </div>

    <div class="control-group form-group">
        <label class="control-label">Asking as (User) :</label>
        <select class="form-control" id="user_select" name="user" >
            <option value="">Select User</option>
        </select>
    </div>
    <button type="submit" class="btn btn-default">Create</button>
</form>

JAVASCRIPT

$(document).ready(function() {

    $.ajax({
        url: "http://localhost:8080/xoxo/api/getAllTags",
        type: "POST",
        dataType: "json",
        crossDomain: true,
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        beforeSend: function (xhr) {
            /////   Authorization header   /////
            xhr.setRequestHeader("Authorization", "Bearer "+token);
        },
        success: function (data) {
            var tags = data.tags;
            $.each(tags,function(i,val){
                $('#tags_select').append('<option value="'+val.name+'">'+val.name+'</option>')
            });
            $('#tags_select').chosen({no_results_text: "Oops, nothing found!",max_selected_options: 3});

        },
        error: function (jqXHR, textStatus, errorThrown) {

        }
    });

    $.ajax({
        url: "http://localhost:8080/xoxo/api/getAllUsers",
        type: "GET",
        dataType: "json",
        crossDomain: true,
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        beforeSend: function (xhr) {
            /////   Authorization header   /////
            xhr.setRequestHeader("Authorization", "Bearer "+token);
        },
        success: function (data) {
            var users = data.users;
            $.each(users,function(i,val){
                $('#user_select').append('<option value="'+val.id+'">'+val.fName+' '+val.lName+'</option>')
            });

        },
        error: function (jqXHR, textStatus, errorThrown) {

        }
    });

    $('#createQueForm').bootstrapValidator({
        live: 'disabled',
        // This option will not ignore invisible fields which belong to inactive panels
        exclude: ':disabled',
        fields: {
            question: {
                validators: {
                    notEmpty: {
                        message: 'Question Text is required.'
                    }
                }
            },
            tags: {
                validators: {
                    notEmpty: {
                        message: 'Tags are required.'
                    }
                }
            },
            user: {
                validators: {
                    notEmpty: {
                        message: 'Asking User is required.'
                    }
                }
            }
        }
    })
    .on('success.form.bv', function(e) {
        // Prevent form submission
        e.preventDefault();

        // Get the form instance
        var $form = $(e.target);

        // Get the FormValidation instance
        var bv = $form.data('bootstrapValidator');

        // Use Ajax to submit form data
        var question = new Object();
        question.questionText = $('textarea[name=questionText]').val();
        question.tags = $('#tags_select').val();
        question.userId = $('#user_select').val();
        $.ajax({
            url: "http://localhost:8080/xoxo/api/createQuestionOnWeb",
            data: question,
            type: "POST",
            dataType: "json",
            crossDomain: true,
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            beforeSend: function (xhr) {
                /////   Authorization header   /////
                xhr.setRequestHeader("Authorization", "Bearer "+token);
            },
            success: function (data) {
                if(data.status == "success"){
                    $('.alert-danger').hide();
                    $('.alert-success').show();
                    location.href = "questions_list.php";
                }else{
                    $('.alert-success').hide();
                    $('.alert-danger').html(data.errorReason).show();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('.alert-success').hide();
                $('.alert-danger').html('Oops..! Something went wrong.').show();
            }
        });
    });     
});

Kindly help figuring out how to enable validation on the multiselect tag with chosen enabled after its options are populated through the Ajax call.

Harsh Reddy
  • 203
  • 6
  • 14

1 Answers1

0

Have had similar problem and couldn't find answers for it. Below is my solution to it maybe it will help someone. There are two problems to address here:

  1. Chosen doesn't use original select/input. It does display:none on it and creates its own div for user input. Following advice here you need to make validate work with hidden fields. Add:

    $.validator.setDefaults({ ignore: ":hidden:not(select)" });

  2. Then, validation on chosen fields works fine, but your ajax async modification disrupts it. Validate picks your populating a dropdown as a user change and assigns success class to it. A way to avoid it is delaying validate for after async executes using when from jquery's toolbox. Wrap your ajax calls and validate initialisation in functions along the lines of:

    $.when(populateAjaxSelects()).then(function(){ initialiseValidate(); });

EDIT: Ok. I used jQuery Validate not bootstrap validator. I think you are dealing with the same general problems here though.

Community
  • 1
  • 1
Burpy Burp
  • 459
  • 3
  • 12