Search code examples
javascripthtmlselectors-api

Cannot get data from form with query selector


I can't get the data from the input of the form, it seems like the only function of the submit button is to refresh the page.

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>


Solution

  • When you look at the JavaScript console of your browser, you'll see that it complains about not being able to read a property of undefined. This is caused by clienti not being defined in your JavaScript code, in the clienti.selectedIndex part. Defining it seems to resolve your issue.

    As a bonus: you may want to consider using selectedOptions to find all selected options in the select, given that it has the multiple attribute. The selectedIndex will only give you the first one.

    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}`);
      }
    })
    <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>