jfjmartin
jfjmartin

Reputation: 61

Html / javascript - Dropdown selection not working with Submit button

I am trying to using a dropdown and an input box and then submit both. For some reason, it is not

function watchForm() {
  $('.decisions').on('click', function(event) {
    event.preventDefault;
    const state = $('.js-query-states').val();
    console.log(state)
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="decisions">

  <select class="states js-query-states">
    <option value="">Choose a state</option>
    <option value="AL">Alabama</option>
  </select><br><br>
  <label for="number">How many</label>
  <input type="input" name="number" id="number" value=5>
  <input type="submit" value="Submit">
</form>

Upvotes: 3

Views: 660

Answers (3)

Cristian Richard
Cristian Richard

Reputation: 26

To submit the value of the "select" DOM element you must set the "name" attribute and then, "submit" button will include it when you clicked on it

<form class = "decisions">

    <select class="states js-query-states" name="state">
        <option value= "">Choose a state</option>
        <option value= "AL">Alabama</option>
    </select><br><br>
    <label for= "number">How many</label>
    <input type = "input" name = "number" id= "number" value = 5>
    <input type="submit" value = "Submit">
</form>

Upvotes: 0

palaѕн
palaѕн

Reputation: 73946

Few issues here:

  • You need to listen to the Form .submit() event instead of click().
  • Also, you are missing the parentheses () after event.preventDefault.
  • Also, it seems that the event handler is inside the watchForm() function, but it is not called anywhere. So, you can remove that function and add the .submit() event handler directly.

$('.decisions').submit(function(event) {
  event.preventDefault();
  const state = $('.js-query-states').val();
  console.log(state)

  const number = $('#number').val();
  console.log(number)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="decisions">
  <select class="states js-query-states" required>
    <option value="">Choose a state</option>
    <option value="AL">Alabama</option>
  </select><br><br>
  <label for="number">How many</label>
  <input type="input" name="number" id="number" value=5>
  <input type="submit" value="Submit">
</form>

Upvotes: 1

Nagaraj .
Nagaraj .

Reputation: 455

It should be event.preventDefault() like Barmar said. Also it's good to have submit event for the form.

Upvotes: 0

Related Questions