[英]How can I make the options appear in a select dynamically?
我正在嘗試在javascript中生成的html中加載以下選項。
HTML:
<button type="submit" onClick="input(data)">Add</button>
<select id="processSelect" name="process">
</select>
Javascript:
function input(input){
//my code
createOptionsSelectProcess(arrayResponse);
}
function createOptionsSelectProcess(arrayResponse){
var html = '';
var arrayLength = arrayResponse.length;
for (var i = 0; i < arrayLength; i++) {
html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i]
+ '</option>';
}
document.getElementById("processSelect").innerHTML = html;
}
但是,我在調試中觀察到的結果是這些選項是在select中生成的,但是在執行完成后它們會消失。 有人知道原因嗎?
按鈕類型提交將提交表單並刷新頁面,使用
<button type="button" onClick="input(data)">Add</button>
同樣,默認情況下,按鈕的類型為Submit,因此,如果您不放置它,它將仍然提交表單。
您不需要功能input(input)
。 您可以使用事件偵聽器submit
來提交表單。
document.addEventListener('submit', () => createOptionsSelectProcess(data)) function createOptionsSelectProcess(arrayResponse) { var html = ''; var arrayLength = arrayResponse.length; for (var i = 0; i < arrayLength; i++) { html += '<option value="'+ arrayResponse[i] +'">' + arrayResponse[i] + '</option>'; } document.getElementById("processSelect").innerHTML = html; }
<form> <button>Add</button> <select id="processSelect" name="process"></select> </form>
您可以使用<button>Add</button>
或<input type="submit" value="Add">
。 他們都將提交沒有onClick
屬性的表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.