gpt4 book ai didi

javascript - 将用户输入添加到数组并更新选项列表

转载 作者:行者123 更新时间:2023-11-30 09:11:56 24 4
gpt4 key购买 nike

所以我有这个页面:

我有一个由数组中的元素组成的列表。如果用户添加新食物,输入应该进入数组并在列表中显示新元素,输入字段应该消失。现在我收到 404 错误。

我该怎么做?

// find elements
var banner = $("#banner-message")
var button = $("button")

var select = document.getElementById("selectFood");
var options = ["Pizza", "Hambruger", "Salad"];

for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}

function foodInput() {
boxvalue = document.getElementById('addedFood').value;
options.push(boxvalue);
}

function addFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#banner-message {
background: #778899;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}


button {
background: #A52A2A;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}

.addButton {
background: #A52A2A;
color: white;
}

#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}

#banner-message.alt button {
background: #fff;
color: #000;
}

.hide {
display: none;
}

.show {
display: block;
}

.demo {
background: #A52A2A;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}

#myDIV {
background: #778899;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
display: none;
}

input[type=submit] {
background: #A52A2A;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>My favorite food</p>
<select id="selectFood">
<option>Select food</option>
</select>
<button>Choose</button>
<br>
<button id="addButton" onclick="addFunction();">
Add new food
</button>
</div>

<div id="myDIV">
<form onsubmit="return foodInput()">
<input type="text" id="addedFood" placeholder="Type food">
<input type="submit" value="Submit" onclick="addFunction()">
</form>
</div>

最佳答案

实际上,我认为问题在于表单在提交时试图重新加载 fiddle Html 页面。

这里是经过一些小优化的修改内容的工作链接。

[https://jsfiddle.net/8rvax5z0/3/]

关于javascript - 将用户输入添加到数组并更新选项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58011834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com