受け入れられた回答でtuanvtのアイデアを使用して、私はその仕事をするjQueryプラグインを作成しました。
ユーザーが上、下、ページアップ、ページダウンのキーを押して、オートコンプリートボックスに入ったことを確認します。他のすべてのキーは、それらがそれを残したことを意味します。
これらのルールをテキストボックスにのみ適用するようにします。他のすべての入力要素は正常に動作します。
Operaは、私が達成しようとしていたことをすでにかなりうまく行っているので、そのブラウザーでルールを適用しません。そうしないと、ユーザーはEnterキーを2回押す必要があります。
IE6、IE7、IE8、Firefox 3.5.5、Google Chrome 3.0、Safari 4.0.4、Opera10.00でテスト済み。
これは、jquery.comでSafeEnterプラグインとして利用できます。便宜上、リリース1.0のコードは次のとおりです。
// jQuery plugin: SafeEnter 1.0
// http://plugins.jquery.com/project/SafeEnter
// by teedyay
//
// Fires an event when the user presses Enter, but not whilst they're in the browser's autocomplete suggestions
//codesnippet:2e23681e-c3a9-46ce-be93-48cc3aba2c73
(function($)
{
$.fn.listenForEnter = function()
{
return this.each(function()
{
$(this).focus(function()
{
$(this).data('safeEnter_InAutocomplete', false);
});
$(this).keypress(function(e)
{
var key = (e.keyCode ? e.keyCode : e.which);
switch (key)
{
case 13:
// Fire the event if:
// - we're not currently in the browser's Autocomplete, or
// - this isn't a textbox, or
// - this is Opera (which provides its own protection)
if (!$(this).data('safeEnter_InAutocomplete') || !$(this).is('input[type=text]') || $.browser.opera)
{
$(this).trigger('pressedEnter', e);
}
$(this).data('safeEnter_InAutocomplete', false);
break;
case 40:
case 38:
case 34:
case 33:
// down=40,up=38,pgdn=34,pgup=33
$(this).data('safeEnter_InAutocomplete', true);
break;
default:
$(this).data('safeEnter_InAutocomplete', false);
break;
}
});
});
};
$.fn.clickOnEnter = function(target)
{
return this.each(function()
{
$(this)
.listenForEnter()
.bind('pressedEnter', function()
{
$(target).click();
});
});
};
})(jQuery);