Jquery Mobile Validation error position & selects

前端 未结 2 1140
臣服心动
臣服心动 2021-01-15 00:12

I added bassistance jQuery validation to a form on my jQuery Mobile project. It works perfect, except for the errors show up inside the text inputs and not below them. I kno

2条回答
  •  孤城傲影
    2021-01-15 00:49

    By default, when using jQuery Validate plugin along with jQuery Mobile, the error messages show up below the input element. Removing your custom errorPlacement callback function...

    Simple DEMO: http://jsfiddle.net/7rXnS/

    $(document).on('pageinit', function () {
    
        $('#registrationForm').validate({
            rules: {
                firstname: {
                    required: true
                },
                lastname: {
                    required: true
                }
            },
            messages: {
                firstname: {
                    required: "Please enter your first name."
                },
                lastname: {
                    required: "Please enter your last name."
                }
            }
        });
    
    });
    

    However, jQuery Mobile wraps select elements within div elements so when the plugin adds the error label it appears to be placed inside of the select element. To fix this, use the errorPlacement callback as follows. It checks to see if the element is a select element and then inserts the error label after the outermost div wrapper. If the element is not a select, it just uses the default placement.

    errorPlacement: function (error, element) {
        if (element.is('select')) {
            error.insertAfter(element.parents('div.ui-select'));
        } else {
            error.insertAfter(element);  // default placement
        }
    }
    

    DEMO using a select: http://jsfiddle.net/QuwkZ/

提交回复
热议问题