Search code examples
javascriptjqueryqtip2

Automatically close qtip2 using JQuery .validate()


I'm working on a form which implements QTip2 to display a tooltip once someone tries to submit a form where data is missing. Everything works as intended, however I would like the tooltip to be removed once the error class is removed (effectively once someone types in the input field). I have the following code for my validation currently:

$('#form0').validate({
    rules: {
        Name: "required",
        Email: {
            required: true,
            email: true
        },
        Subject: "required",
        Message: "required"
    },
    errorPlacement: function (error, element) {
        $('#Name').qtip({
            content: 'Please enter your name',
            position: {
                target: 'mouse', // Track the mouse as the positioning target
                adjust: { x: 5, y: 5 } // Offset it slightly from under the mouse
            },
            style: { classes: 'qtip-red' }
        });
        return true;
    },
    errorClass: "form-error"
});

As you can see, once someone tries to submit the form the class "form-error" is assigned to the input field, so I would like the tooltip to be removed as well once this class is removed. I tried the following, but it did not work, not sure why:

onHide: function() { $(this).qtip('destroy'); }

Solution

  • I found a solution to this problem by adding the following code inside errorPlacement {}:

    events: { show: function (event, api) { if (!element.hasClass('form-error')) event.preventDefault(); } },
    show: {
        delay: 0,
        target: element
    },
    hide: { target: element },