jQuery - Preventing autocomplete select triggering blur()
Asked Answered
A

7

15

I'm trying to prevent blur to happen when select: in autocomplete is called. (select: is called when the item is clicked on suggestion box of autocomplete) However, unintentionally, blur is called when I select an item from a suggestion box. How would I fix this problem?

Here's how my code is basically lined up.

$("#input_field").autocomplete({
    source: "source.php",
    select: function( event, ui ) { alert("Item selected! Let's not trigger blur!"); }
}).blur(function(event) {
    alert("Alert if the user clicked outside the input, pressed enter, or tab button.");
    alert("But not from the item selection! :S");
});

Thank you!

Edit: Here's a brief context. I am trying to allow users to search/select an item or create a new item if the user blurs the input.

Alphonsealphonsine answered 19/4, 2011 at 5:7 Comment(3)
if you could give a bit more context as to why you want to stop blur from happening that would helpSib
Thanks, I hope my brief context helpsAlphonsealphonsine
+1, I ran into the same exact problem. See my answer below.Lesleylesli
L
20

The autocomplete jquery UI widget comes with a "change" event which I think does what you want. It is called just like a blur, except it isn't called when an item is selected with the mouse.

$("#input_field").autocomplete({
    source: "source.php",
    select: function( event, ui ) { alert("Item selected! Let's not trigger blur!"); }
});
$("#input_field").bind('autocompletechange', function(event, ui) {
    alert("Alert if the user clicked outside the input, pressed enter, or tab button.");
    alert("But not from the item selection! :S");
});
Lesleylesli answered 14/12, 2011 at 20:48 Comment(3)
+1 for showing when change is fired.Please vote this as the answer.Hesione
this doesn't seem to work for me. the blur function happens, then i get the 'lets not trigger' alert.Platino
are the two method together or separate? If they are separate, how can the autocompletechange gets the event and ui parameters?Pesach
C
3

Based on what I've seen here I've put two of the code samples together to create what I believe to be the answer; it was for me:

$('#txtCatagory').autocomplete({ source: 'handlers/Catagories.ashx', minLength: 2,
    change: function (event, ui) {
        AddTag(event.srcElement.value);
        $('#txtCatagory').val('');
    },
    select: function (event, ui) {
        event.preventDefault();
        AddTag(ui.item.value);
        $('#txtCatagory').val('');
    }
});

Here's my text box:

<asp:TextBox runat="server" ID="txtCatagory" ClientIDMode="Static" OnKeyPress="return disableEnterKey(event)" />

What this does for me is whatever I type in the text box is passed to the AddTag function or whatever I select from the jQuery UI AutoComplete is passed. But critically it doesn't pass whatever I've typed IF I then use the autocomplete and it clears the box ready for the next input.

As you may have guessed from the name of the function AddTag I use this for tagging posts or products, but thanks to the posts above I have now managed to add autocomplete to that feature.

Croaky answered 21/12, 2011 at 15:5 Comment(0)
S
1

I don't know how to avoid onBlur to trigger, but I think I have the same problem and I have solved it by testing if the autocomplete field is open in the onBlur function.

HTML declaraction

<input id="autocompleteTextbox" type="text" onblur="onBlurFunction();" 
       onkeyup="onKeyUpFunction();" />

Javascript

var autocompleteOpen = false;
var itemSelected = false;

$("#autocompleteTextbox").autocomplete({

    source: function(request, response) {
        //Set source.
    },

    select: function(event, ui) {
        itemSelected = true;
    },

    open: function(event, ui) {
        autocompleteOpen = true;
    },

    close: function(event, ui) {
        autocompleteOpen = false;
        //A selection caused the close. Blur the autocomplete field.
        if (itemSelected) {
            document.getElementById("autocompleteTextbox").blur();
        }
    }
});


function onBlurFunction() {
    if (!autocompleteOpen) {
        //Do stuff.
    }
}

function onKeyUpFunction() {
    itemSelected = false;
}

This way the code in onBlurFunction() will not run if the autocomplete is open. itemSelected is used to test if the user entered the text in the field or selected something from the autocomplete list. In the close function I blur the field if the user has selected something from the list. I don't know if that makes sense in your case.

Sicyon answered 11/10, 2011 at 10:53 Comment(0)
L
0

use event.stopPropagation();

$("#input_field").autocomplete({
    source: "source.php",
    select: function( event, ui ) { alert("Item selected! let's not trigger blur!"); }
}).blur(function(event) {
event.stopPropagation();    
alert("noooooo! blur is still being called!");
});

or you can use event.preventDefault() in same way...

$("#input_field").autocomplete({
        source: "source.php",
        select: function( event, ui ) { alert("Item selected! let's not trigger blur!"); }
    }).blur(function(event) {
    event.preventDefault();  
    });

reference event.preventDefault

Leasia answered 19/4, 2011 at 5:31 Comment(1)
I could not get this to work. i still see the alert after the stop. both use cases.Platino
B
0

You might need to get more specific, but it sounds like you still want some blur function to be called upon blurring, but you don't want it called on initial setup; try something like this...

$('#input_field').data('ready_to_blur',false)
    .blur(function(e) {
         if ($(this).data('ready_to_blur')) 
             return;
         $(this).data('ready_to_blur',true);
         event.stopPropagationImmediate();
    })
    .autocomplete({
         source: "source.php",
         select: function( event, ui ) { alert("Item selected! let's not trigger blur!"); }
    })

I also think you'll want to use stopPropagationImmediate. See the docs: http://api.jquery.com/event.stopImmediatePropagation/

Balthazar answered 19/4, 2011 at 5:42 Comment(2)
I want blur to happen as soon as the user leaves #input_field. But "unintentionally, blur is called when I select an item from a suggestion box. How would I fix this problem?"Alphonsealphonsine
it's "stopImmediatePropagation()", not "e.stopPropagationImmediate()"Ngocnguyen
K
0

a very simple solution for this issue.

unbind blur event handler when dropdown is displaying, and bind blur event handler again after selection.

adding two events when initialising autocomplete

displaydropdowncallback: function(){ $("#AUTOTEXT").unbind("blur"); },
selectdatacallback: function (data) {
    $("#AUTOTEXT").blur(validatepostcode);
}

Modify jquery autocomplete source code:

adding code options.displaydropdowncallback();

under

show: function () {
    var offset = $(input).offset();

adding options.selectdatacallback(selected.data);

under

function selectCurrent() {
        var selected = select.selected();

        if (!selected)
            return false;
Kronos answered 13/6, 2013 at 1:31 Comment(0)
R
-2

Trigger an event when the user blur from a text feild to show him/her a small div with 200px width and 100px height with blue background color and, with a bold text that inform him that "he shouldn't leave this field blank"

Radburn answered 11/1, 2012 at 20:32 Comment(1)
You really should provide some code or fix the code in the question. A jsfiddle is also a good idea.Thanh

© 2022 - 2024 — McMap. All rights reserved.