来自 JavaScript 的 DataList 的值返回未定义
Value of DataList sourced from JavaScript returning undefined
我正在我的网页上创建一个数据列表,它从 Java 脚本数组(使用 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>
此代码正确显示了数据列表,但在提交表单时我调用了另一个包含以下行的 Java脚本函数:
var engineer = document.getElementById('engineer').value;
那个值最终是 undefined
。
您正在尝试错误地获取数据列表的值。选择器必须位于 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
得到datalist值:
var engineer = document.getElementById('engineerList').value;
我正在我的网页上创建一个数据列表,它从 Java 脚本数组(使用 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>
此代码正确显示了数据列表,但在提交表单时我调用了另一个包含以下行的 Java脚本函数:
var engineer = document.getElementById('engineer').value;
那个值最终是 undefined
。
您正在尝试错误地获取数据列表的值。选择器必须位于 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
得到datalist值:
var engineer = document.getElementById('engineerList').value;