0
このスニペットを使用してユーザーが都市リストから選択し、カンマ区切りのテキストエリアに挿入できるようにします。それは動作します。jQuery:オートコンプリートからの値をテキストエリアで指定するように強制します。
私はこの目的を達成したいと思います:ユーザは、コンボボックスのように都市名を検索するために都市名の一部を書きますが、オプションの1つを選択せずにフィールドを離れると、消去する必要があります。
簡単に言えば、フォームを送信する前に、ユーザーが完全な都市名ではない文字列でフィールドを埋めるのを防ぐ一種の検証を実装したいと思います。
アイデア?
ありがとうございました!
jQuery(function() {
var availableTags = [
"Agliè (TO)",
"Airasca (TO)",
//--- the other cities list ---
];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
jQuery('textarea[data-wpt-id=wpcf-comuni-caldo],textarea[data-wpt-id=wpcf-comuni-freddo],textarea[data-wpt-id=wpcf-comuni-alta-potenza]')
//,input[name=wpv-wpcf-comuni-caldo],input[name=wpv-wpcf-comuni-freddo],input[name=wpv-wpcf-comuni-alta-potenza]
// don't navigate away from the field on tab when selecting an item
.on("keydown", function(event) {
if (event.keyCode === jQuery.ui.keyCode.TAB &&
jQuery(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response(jQuery.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function() {
// prevent value inserted on focus
return false;
},
autoFill:true,
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;
}
});
});