下方與法式autocomplete的語法,會將輸入關鍵字做搜尋,並自動選出可填入字
過程中可以連續輸入與選擇,並使用逗號分開
$(function() {
function split( val ) {
//alert(val);
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$("#S1")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "XXX.PHP", {
searchTerm: extractLast( request.term )
}, response );
//alert(response);
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
formatItem: function(row) {
return "<div style='height:12px'><div style='float:left'>" + //row[0] +
"</div>" +
// row[1] + "/" +
"" + row[2] +"</div>";
},
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;
}
});
});
想請教,如果我的textarea,我想保留換行,我該怎麼改,因為即使我換行,他還是會幫我用逗號分開再組合起來
只要改掉 select 這邊的作法就可以了
<pre class="c" name="code">
select: function( event, ui ) {
var term = extractLast( this.value );
// add the selected item
var itemPos = this.value.lastIndexOf(term);
this.value = this.value.substr(0, itemPos) + ui.item.value;
// add comma-and-space at the end
this.value += ", ";
return false;
}