我正在尝试使用自动填充制作购物清单。当你点击添加按钮时,我希望将项目移动到购物清单中,但我得到了未定义的
https://fiddle.jshell.net/ktcle/pbmL2q1e/1/
<input type="text" id="auto" />
<button id="click">
Add to your selection
</button>
<button id="add" class="hidden">Item does not exist. Click here to add it.</button>
<div id="your-selection">
your shopping list
</div>
和js
var source = ["Apples", "Oranges", "Bananas", "Grapes", "Bread", "Milk"];
$(function () {
$("#auto").autocomplete({
source: function (request, response) {
response($.ui.autocomplete.filter(source, request.term));
$('#outputcontent').html(thehtml);
},
change: function (event, ui) {
$("#add").toggle(!ui.item);
}
});
$("#click").on("click", function (request) {
var thehtml = '<strong>Item:</strong> ' + request.source;
$('#your-selection').html(thehtml);
});
$("#add").on("click", function () {
source.push($("#auto").val());
$(this).hide();
});
});
答案 0 :(得分:2)
要获取所选项目,请使用$("#auto").val()
。请检查以下代码。
$("#click").on("click", function () {
var newSelected = $("#auto").val();
var thehtml = '<br/>' + $("#auto").val();
var selectedItems = $('#your-selection').html();
if(selectedItems.indexOf(newSelected) === -1){
$('#your-selection').append(thehtml);
}else{
alert("Already selected!");
}
$("#auto").val('');
});
请查看以下代码段以获取更多理解
var source = ["Apples", "Oranges", "Bananas", "Grapes", "Bread", "Milk"];
$(function () {
$("#auto").autocomplete({
source: function (request, response) {
response($.ui.autocomplete.filter(source, request.term));
//$('#outputcontent').html(thehtml);
},
change: function (event, ui) {
$("#add").toggle(!ui.item);
}
});
$("#click").on("click", function () {
var newSelected = $("#auto").val();
var thehtml = '<br/>' + $("#auto").val();
var selectedItems = $('#your-selection').html();
if(selectedItems.indexOf(newSelected) === -1){
$('#your-selection').append(thehtml);
}else{
alert("Already selected!");
}
$("#auto").val('');
});
$("#add").on("click", function () {
source.push($("#auto").val());
$(this).hide();
});
});
.hidden { display: none; }
#your-selection{margin: 1em 0; background: pink; width: 200px; padding: 10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" id="auto" />
<button id="click">
Add to your selection
</button>
<button id="add" class="hidden">Item does not exist. Click here to add it.</button>
<div id="your-selection">
your shopping list Items
</div>