Search code examples
jqueryjquery-validatetooltipster

jquery validation with tooltipster error message placement issue for multiple checkbox


I'm using jquery validate with the tooltipster to show the error messages as tooltips instead of default. The issue I'm having is the error message placement for multiple checkboxes. I want to show on the main label(which is Location in this case) instead of showing on the first checkbox. Below is the sample code,

Form:

<form id="myform">
    <label for="location">Location</label>
    <br/>
    <label for="telf_local">In state</label>
    <input type="checkbox" id="telf" name="telf" value="1" />
    <label for="telf_movil">Out of state</label>
    <input type="checkbox" id="telf" name="telf" value="2" />
    <br/>
    <input type="submit" />
</form>

JS:

$(document).ready(function () {

    // initialize tooltipster on text input elements
    $('#myform :input').tooltipster({
        trigger: 'custom',
        onlyOne: false,
        position: 'right'
    });

    // initialize validate plugin on the form
    $('#myform').validate({
        errorPlacement: function (error, element) {

            var lastError = $(element).data('lastError'),
                newError = $(error).text();

            $(element).data('lastError', newError);

            if (newError !== '' && newError !== lastError) {
                $(element).tooltipster('content', newError);
                $(element).tooltipster('show');
            }

        },
        success: function (label, element) {
            $(element).tooltipster('hide');
        },
        rules: {
            telf: {
                required: true
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form');
            return false;
        }
    });

});

Solution

  • The issue I'm having is the error message placement for multiple checkboxes.

    You're configuring/initializing ToolTipster for all input elements at once...

    $('#myform :input').tooltipster({
        trigger: 'custom',
        onlyOne: false,
        position: 'right'  // <- same position for everything
    });
    

    Instead, configure/initialize ToolTipster for each input element type. Then you can set custom placement options for the checkbox tooltips.

    // text inputs
    $('#myform input[type="text"]').tooltipster({
        trigger: 'custom',
        onlyOne: false,
        position: 'right'
    });
    
    // checkbox inputs
    $('#myform input[type="checkbox"]').tooltipster({
        trigger: 'custom',
        onlyOne: false,
        // your custom positioning options here
    });
    

    See the examples here.