0

I have some JavaScript below, but it doesn't work unless I have the alert as shown below. I know this is some sort of timing issue, but I have no idea how to go about fixing it. Any thoughts?

$(function() {
    $("#search_field").tokenInput("/searches/suggest_gems.json", {
    onAdd: function (item) {
    $('#search_field').val(item.name);
    // Doesn't work without alert("hi");
    },
    crossDomain: false,
    tokenLimit: 1,
    tokenValue: name
    });
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
areke
  • 1,093
  • 1
  • 14
  • 23
  • 1
    What does this mean? "Does not work without alert"? What is this supposed to do? What are your errors? What exactly are we fixing? – Sparky Jan 07 '13 at 21:20
  • You might want to set an interval with `setInterval()` or use `setTimeout()` (look for those on Google, they might help you out) ! – Jeff Noel Jan 07 '13 at 21:21
  • 1
    Yes it does, it's just that the `alert()` pauses things long enough for something else to catch up behind the scenes. – David Thomas Jan 07 '13 at 21:22

2 Answers2

1

I've run into similar issues before. What I've found to work is using $(window).load(function(){...}) instead of $(function(){...}). This buys enough time to let anything that's not ready by the time the DOM is loaded to be ready by the time the window is loaded fully. Hope this helps.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

try checking the console for errors. In Chrome you can make the console persistent :https://stackoverflow.com/a/7661797/1446608

Sounds like an async problem. When you are using the alert, code execution stops, and the error does not show. If you are not using the alert, an error stops code executions, so onAdd is never fired, so that code won't be executed.

To start, try checking if the element #search_field still exists in the DOM when onAdd is fired.

Check also that item.name is not undefined.

Check what happens before onAdd is fired.

Community
  • 1
  • 1
Mihai
  • 217
  • 1
  • 3