Skip to content Skip to sidebar Skip to footer

Unable To Add Class In Input Of Select2 Upon Validation

I am using select2.js. This is the html i am using for my form.
  • Solution 1:

    Here is an exemple of form validation with select2 validating in JS.

        <form id="select2Form" method="post" class="form-horizontal">
            <select name="colors" class="form-control select2-select"
                multiple data-placeholder="Choose 2-4 colors">
                <option value="black">Black</option>
                <option value="blue">Blue</option>
                <option value="green">Green</option>
                <option value="orange">Orange</option>
                <option value="red">Red</option>
                <option value="yellow">Yellow</option>
                <option value="white">White</option>
            </select>
        </form>
    

    And the js to validate :

    $('#select2Form')
        .find('[name="colors"]')
            .select2()
            // Revalidate the color when it is changed
            .change(function(e) {
                $('#select2Form').formValidation('revalidateField', 'colors');
            })
            .end()
        .formValidation({
            framework: 'bootstrap',
            excluded: ':disabled',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                colors: {
                    validators: {
                        callback: {
                            message: 'Please choose 2-4 color you like most',
                            callback: function(value, validator, $field) {
                                // Get the selected options
                                var options = validator.getFieldElements('colors').val();
                                return (options != null && options.length >= 2 && options.length <= 4);
                            }
                        }
                    }
                }
            }
        });
    

Post a Comment for "Unable To Add Class In Input Of Select2 Upon Validation"