我无法从表单的输入中获取数据,似乎提交按钮的唯一功能是刷新页面。
const Form = document.querySelector('.broadcast-form')
Form.addEventListener('submit', (e) => {
e.preventDefault()
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
console.log(cliente)
})
<form class="container broadcast-form">
<select multiple class="form-control" id="clienti" style="height: 150px" onchange="selectCustomer()">
<!--
<% for(var i=0; i<clienti.length; i++) {%>
<option><%= clienti[i]["Cliente"] + " CL: " + codiceLisa[i]["Codice_Lisa"] %></option>
<% } %>
-->
<option>Foo CL: ABC</option>
<option>Bar CL: DEF</option>
<option>Baz CL: GHI</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Genera XML" />
</form>
答案 0 :(得分:1)
当您查看浏览器的JavaScript控制台时,您会发现它抱怨无法读取undefined
的属性。这是由clienti
部分的JavaScript代码中未定义clienti.selectedIndex
引起的。定义它似乎可以解决您的问题。
作为奖励:您可能需要考虑使用selectedOptions
在选择中查找所有选定的选项,因为它具有multiple
属性。 selectedIndex
只会给你第一个。
function selectCustomer() {
/* defined only to prevent errors when changing the value of the select */
}
const form = document.querySelector('.broadcast-form');
form.addEventListener('submit', (e) => {
e.preventDefault()
let clienti = form.querySelector('#clienti'),
cliente = (clienti.selectedIndex < 0 ? null : clienti.options[clienti.selectedIndex].text);
console.log(cliente);
// bonus:
for (let clienteEl of clienti.selectedOptions) {
console.log(`bonus: ${clienteEl.text}`);
}
})
&#13;
<form class="container broadcast-form">
<select multiple class="form-control" id="clienti" style="height: 150px" onchange="selectCustomer()">
<!--
<% for(var i=0; i<clienti.length; i++) {%>
<option><%= clienti[i]["Cliente"] + " CL: " + codiceLisa[i]["Codice_Lisa"] %></option>
<% } %>
-->
<option>Foo CL: ABC</option>
<option>Bar CL: DEF</option>
<option>Baz CL: GHI</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Genera XML" />
</form>
&#13;