我正在我的网页上创建一个数据列表,该数据列表从JavaScript数组(使用JSP从Java数组中获取)获取其值。
这是我用于填充数据列表的代码:
<input name="Engineer Name" list="engineer" />
<datalist id="engineer"></datalist>
<script>
//Take the engineers array and transfer to javascript array
//This is so we can source the Engineer Drop-Down menu from a file dynamically
var engineerArray = [];
<% for (int i=0; i<engineers.size(); i++) { %>
engineerArray[<%= i %>] = "<%= engineers.get(i) %>";
<% } %>
for (var i in engineerArray) {
var datalist = document.getElementById('engineer');
datalist.innerHTML += '<option value=' + engineerArray[i] + '>';
}
</script>
此代码正确显示了数据列表,但是在提交表单时,我调用了另一个包含以下内容的JavaScript函数:
var engineer = document.getElementById('engineer').value;
该值最终为undefined
。
答案 0 :(得分:0)
您正在尝试错误地获取数据列表的值。选择器必须位于input
元素上。我已经修改了代码以供参考:
<input name="Engineer Name" id="engineerList" list="engineer" />
<datalist id="engineer"></datalist>
<script>
//Take the engineers array and transfer to javascript array
//This is so we can source the Engineer Drop-Down menu from a file dynamically
var engineerArray = [];
<% for (int i=0; i<engineers.size(); i++) { %>
engineerArray[<%= i %>] = "<%= engineers.get(i) %>";
<% } %>
for (var i in engineerArray) {
var datalist = document.getElementById('engineer');
datalist.innerHTML += '<option value=' + engineerArray[i] + '>';
}
</script>
然后通过指定正确的id
获取数据列表值:
var engineer = document.getElementById('engineerList').value;