我有一个下拉菜单,是从这样的数组生成的(为了简洁起见,在本示例中使用假数据)
var city = document.getElementById("city");
locarr = ["1", "2", "3", "4"];
for(var i=0; i < locarr.length; i++) {
var opt = locarr[i];
var el = document.createElement("option");
el.text = opt;
el.value = opt;
city.add(el);
}
效果很好,它填充了菜单。但是,当我提交表单并重新加载页面时,我想显示初始选定的项目,然后显示数组中除该项目之外的所有其他项目,这样我就不会出现重复的条目。
我的 oldInput.city
值来自 Controller ,该值是在表单提交时发布的值。
在当前状态下,一旦提交表单,我就会有重复的值。
<select class="chosen-select-no-single" name="city" id="city">
<% if (!oldInput.city) { %>
<option value="">Select City</option>
<% } else { %>
<option value="">Select City</option>
<option value="<%= oldInput.city %>" selected>
<%= oldInput.city %>
</option>
<% } %>
</select>
最佳答案
只需从 HTML 中删除 oldInput 即可。在 for 子句中,您可以执行以下操作:
for(var i=0; i < locarr.length; i++) {
var opt = locarr[i];
var el = document.createElement("option");
el.text = opt;
el.value = opt;
var oldInpt="<%=oldInput%>";
if (oldInpt!=null && opt ==oldInpt.city){
el.selected = true;
}
city.add(el);
}
关于javascript - 表单提交后显示不在数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54597664/