Multiple jQuery functions and autocomplete

I found that using jQuery Autocomplete declaration as the first function of your script prevents other functions from being executed.

The second and third functions below will not work:

<script>
$(function() {
    $("#ent_input").autocomplete('get_suggestions', 
        {autoFill: true, scroll: false});
});

    // Freebase Suggest
$(function() {
    $("#ent_input_fb").suggest({type:'/film/director'});
});

$(function() {
    $("#ent_input_fb2").suggest({type:'/film/actor'});
});
</script>

      

However, if I move the autocomplete to the bottom, the other script works, but the autocomplete won't.

<script>
    // Freebase Suggest
$(function() {
    $("#ent_input_fb").suggest({type:'/film/director'});
});

$(function() {
    $("#ent_input_fb2").suggest({type:'/film/actor'});
});

    $(function() {
    $("#ent_input").autocomplete('get_suggestions', 
        {autoFill: true, scroll: false});
});
</script>

      

Has anyone faced similar issues with jQuery Autocomplete ?

+2


source to share


1 answer


jQuery should execute all your handlers $(function()...)

in the order they were declared without issue. It looks like your calls to autocomplete

and suggest

are the culprit.

jQuery is very careful about event handlers, and if you tried to do something like the above with click handlers, you'll notice that they are executed sequentially too (instead of overwriting each other). Try:

Suppose some element is marked as follows:

<span id="someElement" onclick="alert('Me First!');" />

      

... and JavaScript

$("#someElement").click
(
  function()
  {
    alert("1");
  }
);

$("#someElement").click
(
  function()
  {
    alert("2");
  }
);

      



You will see three warning boxes, shown in the following order: "Me first!", "1" and "2".

jQuery adds the extra mile to keep checked onclick handlers as the first function to click when an event occurs. This makes it very safe to use this library with server-side technology like ASP.NET that sprinkles onclick handlers all over the place.

To remove all jQuery related click event handlers from an element, follow these steps:

$("#someElement").unbind("click");

      

Be aware that this does not remove a click handler assigned in a different way (i.e. the onclick attribute in the markup).

+3


source







All Articles