JQuery UI remove tooltip on successful input

45 Views Asked by At

I'm working on a text input with an autocomplete and a tooltip on failed input, using JQuery UI for both the tooltip and the autocomplete. The logic is the following:

  1. There's a set of possible values to enter that are shown as people start writing on the input
  2. If someone decides to keep writing, not select anything from the autocomplete list and press the "search" button, the input text gets cleared and a tooltip saying "Please enter a valid district" is raised.

My problem is, afterwards, if someone enters a valid district, the tooltip still appears on text input focus. So, how can I kill my tooltip after correctly sending an input? I tried this but didn't work:

$(document).ready(function(){
    var availableTags;

    $('#form-district').uitooltip({
                            position: { my: "left bottom", at: "left top" }

                        }).uitooltip('open')

    $.ajax({
        url: '/_autocomplete'
    }).done(function (data){
        availableTags = data;
        var lowerCaseTags = availableTags.map(element => {
         return element.toLowerCase()
        })
        $('#district_autocomplete').autocomplete({

            source: function(request, response) {

                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(data, function(item){
                    return matcher.test(item);
                }));
            },
            minLength: 1,
            change: function (event, ui) {
                if (!ui.item) {
                    var userInput = $(this).val().toLowerCase();
                    if (!lowerCaseTags.includes(userInput)) {
                        $(this).val('');
                        $(this).attr('title', 'Please enter a valid district').uitooltip({
                            position: { my: "left top-100", at: "left bottom" }

                        }).uitooltip('open');
                    }
                } else{
                  $(this).uitooltip('remove'); // my try
                }
            },
            autoFocus: true,
            appendTo: "#formdistrict .input-group"
        });


    });

});

PS: had to bridge ui.tooltip to uitooltip because I'm also loading BS5.

1

There are 1 best solutions below

0
Mohd Ruman On

The method uitooltip is not part of jQuery UI. Instead, it should be tooltip. So, you should use tooltip instead of uitooltip.

In the change event handler of the autocomplete widget, you're trying to initialize a tooltip using uitooltip method again. Instead, you should use the tooltip method to remove the tooltip.

Check if it works.

// Remove tooltip if an item is selected
                $(this).tooltip('destroy');