我正在尝试添加新的下拉字段,当点击添加按钮并且其工作正常但是当我添加一些动态下拉框并填充值并单击添加按钮以获取新的下拉框时,所有上述值被删除,所以如何在不删除现有值的情况下添加?
以下是代码
<script>
function addNew () {
var NumOfField = document.getElementById('fields').value;
NumOfField = Number(NumOfField)+1;
document.getElementById('fields').value = NumOfField;
document.getElementById('newEvent').innerHTML += "<br><br><br><label class='control-label col-md-3 col-sm-3 col-xs-12'>Select </label><div class='col-md-9 col-sm-9 col-xs-12'><select class='form-control' name='event"+NumOfField+"'><option value='select'>Select</option><option value='1'>foo</option></option><option value='2'>baar</option></select></div>";
}
</script>
<body>
<input type="hidden" value="1" id="fields" name="fields">
<div class="form-group" id="newEvent">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Select Step 1</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<select class="form-control" name="event1">
<option value="select">Select</option>
<option value="1">foo</option>
<option value="2">bar</option>
{% endfor %}
</select>
</div>
</div>
<button type="button"onclick="addNew();">Add</button>
答案 0 :(得分:1)
这非常简单,只需查看我在代码段中提供的示例。
它会像你在问题中一样使用bootstrap。但我删除了所有的sceleton以提供整洁的答案。
度过美好的一天!
<select id="example">
<option value="select">Select</option>
<option value="1">foo</option>
<option value="2">bar</option>
</select>
<hr/>
Value: <input type="text" id="val" />
<br/>
Option body: <input type="text" id="text" />
<button id="button">Add new option</button>
<script>
var anchor = document.getElementById("example")
function addNew() {
var anchor = document.getElementById("example")
var val = document.getElementById("val").value
var text = document.getElementById("text").value
alert(val+"=>"+text)
if (val && text) {
alert("adding new option")
var option = document.createElement("option")
option.classList.add("example")
option.classList.add("example2")
option.name = "for php"
option.id = "you know"
option.value = val
option.text = text
anchor.appendChild(option)
} else {
alert("fill the fields")
}
}
document.getElementById("button").onclick = addNew
</script>
&#13;