我很难将选择的自动完成值附加到文本区域以构建句子。换句话说,随着用户从自动填充中选择值,他们将被插入到default_text_1
和default_text_2
之间。
这里的最终目标是附加原始的选定值,并能够从文本区域内联删除选择。
HTML
<input type="text" id="pieces" />
<br />
<textarea id="textarea" rows="4" cols="50"></textarea>
JS
var default_text_1 = "Colors to enjoy are: ";
var default_text_2 = ". There may be others.";
$("#textarea").val(default_text_1 + default_text_2);
var availableColors = [ { label: "Blue", value: "1" }, { label: "Yellow", value: "2" }, { label: "Green", value: "3" } ];
$( "#pieces" ).autocomplete({
select: function( event, ui ) {
source: availableColors;
$("#textarea").val(default_text_1 + availableColors.val + default_text_2);
}
});
答案 0 :(得分:1)
您的选项对象存在一些小问题:
{
select: function( event, ui ) {
source: availableColors;
$("#textarea").val(default_text_1 + availableColors.val + default_text_2);
}
}
source
不应出现在select
的功能中availableColors.val
不存在(我假设您想连接所选的label
我相信这将帮助您前进:
var default_text_1 = "Colors to enjoy are: ";
var default_text_2 = ". There may be others.";
$("#textarea").val(default_text_1 + default_text_2);
var availableColors = [ { label: "Blue", value: "1" }, { label: "Yellow", value: "2" }, { label: "Green", value: "3" } ];
$("#pieces").autocomplete({
source: availableColors,
select: function ( event, ui ) {
let val = $("#textarea").val();
$("#textarea").val(
val.split(default_text_2)
.concat([ui.item.label, default_text_2])
.join(' ')
);
//Remove next two statements if you don't want #pieces cleared
$('#pieces').val('');
return false;
}
});
@import 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<input type="text" id="pieces" />
<br />
<textarea id="textarea" rows="4" cols="50"></textarea>
您可能希望在选择时清除#pieces
,以便不显示选择值。
答案 1 :(得分:0)
尝试此工作代码
var default_text_1 = "Colors to enjoy are: ";
var default_text_2 = ". There may be others.";
$("#textarea").val(default_text_1 + default_text_2);
var availableColors = [{
label: "Blue",
value: "1"
},
{
label: "Yellow",
value: "2"
},
{
label: "Green",
value: "3"
}
];
$("#pieces").autocomplete({
source: availableColors,
select: function (event, ui) {
$("#textarea").val(default_text_1 + ui.item.label + default_text_2);
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" ></script>
<input type="text" id="pieces" />
<br />
<textarea id="textarea" rows="4" cols="50"></textarea>