Manojpabani
Manojpabani

Reputation: 41

Fix glyphicon aspect when datepicker is a required field

I have a form with a datepicker that's being validated using ParsleyJS. The datepicker has a glyphicon next to the input and the input is required.

When the user didn't enter any date, Parsley displays an error. However, when this occurs, the glyphicon span gets a strange behaviour and doesn't match the height of the input.

Below is the code I'm using and a demo of what's happening (check the date input).

What can I do to solve this?

<form>
    <div class="row">
        <div class='col-sm-6'>
            <div class="form-group">
                <div class='input-group date' id='datetimepicker2'>
                    <input type='text' class="form-control" data-parsley-required="true" />
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-xs-6">
            <input type="submit" />
        </div>
    </div>
</form>

<script>
    $(function() {
        $('#datetimepicker2').datetimepicker();
        $('form').parsley();
    });

</script>

enter image description here

Upvotes: 1

Views: 338

Answers (1)

Lu&#237;s Cruz
Lu&#237;s Cruz

Reputation: 14970

Your issue is that Parsley always positions the <ul> with the errors right next to the elements with errors, but in some particular cases, such as yours, you want as a child of another element (in your case you want it to be at the same level as <div class="input-group date">.

So you can use the parsley:field:error event to accomplish that. Try the following code, and be sure to update div.date according to your HTML.

$.listen('parsley:field:error', function(parsleyField) {
    var elem = parsleyField.$element;

    // Whenever we're dealing with datepickers
    if (elem.parent('div.date').length > 0) {
        // Get the parent element of the input
        var topParent = elem.parent('div.date').parent('div');

        // Find the error list and append it to the parent instead of the input
        topParent.find('ul.parsley-errors-list').each(function() {
            // move $(this) to the bottom of top parent
            topParent.append($(this));
        });
    }
});

Check this jsfiddle demo.

Upvotes: 1

Related Questions