【发布时间】:2014-03-13 15:35:00
【问题描述】:
我创建了一个带有类似于 SO 的标签的自动完成功能。
它从我的数据库中抓取数据并将数据作为逗号分隔的标签插入到表单字段中。
eg. PHP, JS, SO, Laravel
我希望它在第 4 个逗号之后停止,因此用户最多可以输入 4 个标签。
不幸的是,有一个问题。输入字段在第 4 个标签后冻结。用户不能删除或编辑标签。
我不知道问题是什么。
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#themeti" )
.keypress(function (e) {
var input = $(this).val()+String.fromCharCode(e.which);
if (input.split(',').length > 4) {
e.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "../../assets/php/themedata.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
【问题讨论】:
-
你错过了“String.fromCharCode(e.which)”
标签: javascript jquery autocomplete