我创建了一个标签类似于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;
}
});
});
答案 0 :(得分:0)
你错过了 String.fromCharCode(e.which)
此
var input = $(this).val();
应该是
var input = $(this).val()+String.fromCharCode(e.which);
答案 1 :(得分:0)
这就是我最终做的事情
$( "#themeti" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.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 );
if(terms.length <= 4) {
// 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;
} else {
var last = terms.pop();
$(this).val(this.value.substr(0, this.value.length - last.length - 2)); // removes text from input
$(this).effect("highlight", {}, 1000);
$(this).addClass("red");
$("#warnings").html("<span style='color:red;'>Max people reached</span>");
return false;
}
}