Skip to content
Advertisement

Javascript: Form submit event not triggering

I am trying to get submit event triggered for my form and for some reason it is not being activated…

I have added a button to the form of type submit and have a script at the end of the body that references the javascript functions related to the form…

Any ideas??

html

{% extends "layout.html" %}

{% block title %}Upload{% endblock %}

{% block body %}

<div class="container">
  <form action="/upload" id="upload-form" method="POST" enctype="multipart/form-data"></form>
  <div class="form-group">
    <h1>Upload</h1>
    <p>Use this form to upload a json file.</p>
  </div>
  <div class="form-row">
    <div class="form-group">
      <label for="file-input">JSON file</label>
      <input type="file" accept=".json" class="form-control-file" id="file-input" />
    </div>
  </div>
  <div class="form-row">
    <pre id="file-contents"></pre>
  </div>
  <button id="clear-button" type="reset" class="btn btn-primary" disabled="true">Clear</button>
  <button id="submit-button" type="submit" class="btn btn-primary" disabled="true">Submit</button>
  </form>
</div>

<script src="/static/js/script.js"></script>

{% endblock %}

script.js

/**
 * Event handler for form submission
 */
document.querySelector("#upload-form").addEventListener('submit', async event => {

    console.log("FORM SUBMIT HANDLER");

    event.preventDefault();

    const formData = new FormData(event.target);
    const fileString = formData.get('file-contents');

    const payload = JSON.stringify({
        file: fileString
    });

    console.log("SENDING : " + payload);

    const response = await sendFile(payload);

    console.log(response);
});

Advertisement

Answer

You’re having an extra misplaced </form> closing tag immediately following the opening tag for your form. Just remove it and it should work fine.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement