Form submit with JS

I have a simple form with a select and submit and I wanted to remove the submit button and submit the form when the selected option changes.

<form method="post">
  <div class="form-group">
    <select name="hall_id" required class="form-control" id="hall">
      <option value="" disabled selected>Select Hall</option>
      <option value="2">Pavillion</option>
      <option value="3">Village Hall</option>
      <option value="4">Church Hall</option>
    </select>
  </div>
  <button type="submit" name="add" class="btn btn-primary">Submit</button>
</form>

I added the following JS at the bottom of the page and it half works. It will accept/recognise the change on the second and susequent changes but not on the first change.

document.querySelector("#hall").addEventListener("change", function(){
  this.form.submit();
})

This sounds not very logic to me :slight_smile:

Did you put the add event listener code inside of onload()?

I don’t follow you @Thallius; what is not logical? The JS is just at the bottom of the page as given. I realise I’m being a numpty but I’m just not sure where.

Instead of:
this.form.submit();
try:
document.getElementsByName("add")[0].click();

1 Like

I only meant that this error makes no sense for me. nothing to do with your code :slight_smile:

Can you just try

window.onload(function() 
{
    document.querySelector("#hall").addEventListener("change", function(){
      this.form.submit();
    })
}

I don’t think this will help but I have no better idea :slight_smile:

1 Like

Thanks @Thallius and @Archibald. I have found the error. The JS wasn’t being loaded first time round, so no message in the console.

I told you I was a numpty! :blush:

1 Like