开发者

jQuery Autocomplete and on change Problem

开发者 https://www.devze.com 2023-02-10 09:47 出处:网络
I have a Textbox with the id text (\"#text\") with has an autocomplete like that: $(\"#text\").autocomplete(data);

I have a Textbox with the id text ("#text") with has an autocomplete like that:

$("#text").autocomplete(data);

this works fine. Now i want three things:

a) If the user clicks on a autocomplete option -> search for that

b) If the user types something and an autocomplete action is shown but he clicks somewhere else -> search for that string he typed

c) If the use开发者_开发知识库r types something that has to autocomplete and clicks somewhere else (change event) -> search for that string he typed

Sounds easy to me but i cant get it to work. At the Moment i have something like that:

$("#text").result(function(e) {
    $("#text").trigger("change");
});
$("#text").change(function(e){
    $(".x").load(...);  
});

If i dont use that trigger, than a) does not work at all, if i type "a" and click on an autocomplete option, "#text" contains "a" in the change function. So the change fires before the value is changed. My thought is that this would be no problem as then shortly after that the result fires the trigger again now with the right value, but that does not happen.

Like this it sometimes works but not all the time. I tried lots and lots of stuff and some worked better and some worse but nothing was correct all the time. How do i do this the right way?


I've never worked with the autocomplete that you're using, but here's a tool you should include in your JavaScript problem-solving toolbox.

When an event fires immediately before another event and you need to wait for the second event to complete before processing the first, use setTimeout(...). There are times where it looks like a delay is required, but more often than not, you just need a few nested calls to setTimeout(..., 0)

function onIdle(fn, loops) {
  loops = loops == null ? 1 : loops;
  if (loops > 0) {
    setTimeout(function() { onIdle(fn, loops - 1); }, 0);
  } else {
    fn();
  }
}

With the above code, you could do something like this in your onChange handler:

onIdle(function() { ... }, 5);

That would call setTimeout consecutively, 5 times. On the fifth time (after which the other event should have completed), you can process the change and use the new value.

0

精彩评论

暂无评论...
验证码 换一张
取 消