无法从带有查询选择器的表单中获取数据

时间:2018-04-10 07:59:02

标签: javascript html selectors-api

我无法从表单的输入中获取数据,似乎提交按钮的唯一功能是刷新页面。

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>

1 个答案:

答案 0 :(得分:1)

当您查看浏览器的JavaScript控制台时,您会发现它抱怨无法读取undefined的属性。这是由clienti部分的JavaScript代码中未定义clienti.selectedIndex引起的。定义它似乎可以解决您的问题。

作为奖励:您可能需要考虑使用selectedOptions在选择中查找所有选定的选项,因为它具有multiple属性。 selectedIndex只会给你第一个。

&#13;
&#13;
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;
&#13;
&#13;