Question

I found that using declaring jQuery Autocomplete as the first function in 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 autocomplete to the bottom, the other script works, but autocomplete doesn'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 run into any similar issues with jQuery Autocomplete?

Was it helpful?

Solution

jQuery should execute all of your $(function()...) handlers in the order they have been declared without issue. It looks like your calls to autocomplete and suggest are the culprits.

jQuery is extremely cautious about event handlers, and if you tried to do something similar to the above with click handlers you'll notice that they too execute in sequence (rather than overwrite each other). Try it:

Assume someElement is marked up as follows:

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

...and the JavaScript

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

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

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

jQuery goes the extra mile to retain your marked up onclick handlers as the first function to click when the event occurs. This makes it very safe to use this library with server-side technology like ASP.NET, which sprinkles onclick handlers all over the place.

To remove all jQuery-assigned click event handlers from an element, do the following:

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

Bear in mind that this does not remove a click handler assigned some other way (i.e., the onclick attribute in markup).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top