twitter-bootstrap 在 select2 中捕获回车键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20781634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
capturing enter key in select2
提问by Muatik
I'm using select2to present an editable selectbox. When user writes a statement which does not appear in the list(select2, data), I show a button to add this statement to the list.
我正在使用select2来呈现一个可编辑的选择框。当用户编写未出现在 中的语句时list(select2, data),我会显示一个按钮以将此语句添加到列表中。
Forcing users to click the button seems to me a little bit frustration. Is it possible to capture enter key in select2? I want to make user able to add his/her new statements into the list just by pressing enter key.
强迫用户点击按钮在我看来有点沮丧。是否可以在 select2 中捕获回车键?我想让用户只需按 Enter 键就可以将他/她的新语句添加到列表中。
采纳答案by Vishal
$('select2-search-field > input.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
addToList($(this).val());
});
回答by Baqer Naqvi
I am using Select2 4.0. This works for me;
我正在使用 Select2 4.0。这对我有用;
$('.select2-search__field').on('keyup', function (e) {
if (e.keyCode === 13)
{
alert('Enter key');
}
});
回答by aleixfabra
I'm using Select2 4.0.3and this works form me:
我正在使用Select2 4.0.3,这对我有用:
$(document).on('keyup', '.select2-search__field', function (e) {
if (e.which === 13) {
alert('Pressed enter!');
}
});
回答by okay56k
回答by Ali
This code can help you with class-based selections:
此代码可以帮助您进行基于类的选择:
$('.select2-selection').on('keyup', function(e) {
var YOUR_SELECT2_CUSTOM_CLASS = $(this).attr('aria-labelledby').includes('YOUR_SELECT2_CUSTOM_CLASS')
if (YOUR_SELECT2_CUSTOM_CLASS && e.keyCode === 13) {
alert($(".YOUR_SELECT2_CUSTOM_CLASS").val())
}
});
Or you can use this:
或者你可以使用这个:
$("YOUR_CUSTOM_CLASS").bind("change keypress", function() {
if (window.event.keyCode === 13) {
alert("Enter Captured")
}
})

