开发者

Stop jQuery autocomplete from focussing the input field after chosen from the dropdown

I'm using the jQuery autocomplete p开发者_Go百科lugin from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ When a user selects a result from the dropdown, the input field gets focused. How can I stop the plugin from doing that? I made it work using the tip from this post: jQuery autocomplete plugin not focusing the next clicked field But this only works when the user uses the mouse to select the results. Then the input field doesn't get focussed. But when the user uses the ENTER-key or the TAB-key, the input still get's focus.

Anyone knows how I can change this so that when a user has selected a value from the dropdown, the input field ddoen't get focussed?

Thank you very much in advance!

Regards, Kim


By the looks of this line in the plugin's selectCurrent() function:

$input.trigger("result", [selected.data, selected.value]);

...a "result" event is triggered on the autocomplete input whenever an option is selected, by mouse or by keyboard.

You can bind to that same event and put the focus on the next control in the form (which I assume is what you want, rather than just removing focus from the current one?):

$("input").bind("result", function () {

   // Get all controls on the form
   var controls = $(this).closest("form").find("input, textarea, select, button");

   // Find the index of the next control
   var nextIndex = controls.index(this) + 1;

   // Check if this is already the last control, so wrap around to the first one
   if (nextIndex >= controls.length) nextIndex = 0;

   // Put focus on the "next" control
   controls.eq(nextIndex).focus();

});


Have you tried jQuery UI's autocomplete plugin? Half of the problem is solved – when you press Tab to close the autocomplete, the input field loses focus. When pressing Enter, it's still focused, but this can be fixed easily:

$('#myInput').keyup(function() {
  // when Enter is pressed
  if (event.which === 13) {
    $(this).blur();
  }
});

Edit

jQuery normalizes the event object, so passing it as an argument is unneccessary.


$( "#to" ).autocomplete({
    source: availableTags,
    select: function (event, ui) {
        $( "#to" ).val( ui.item.label );
        $('#to').blur();
        return false ;
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜