Home > Mobile >  How to call Javascript function and pass elements with HTML button?
How to call Javascript function and pass elements with HTML button?

Time:12-08

I am trying to implement a Javascript function within an HTML button. Below is the Javascript and HTML that I am using. I want the submit button to call the function with the file_name and file_data being passed into the function, but I am not exactly sure how to do this. I know there is an onClick I can use, but I don't know how to pass the information from the file input into the function.

<form method="POST">
  <div align="center">
    <input type="file" id="myfile" name="myfile">
  </div>
  <br />
  <div align="center">
    <button type="submit" class="btn btn-primary">Add File</button>
  </div>
</form>
function uploadFile(file_name, file_data) {
  fetch("/upload-file", {
    method: "POST",
    body: JSON.stringify({ file_name: file_name, file_data: file_data }),
  }).then((_res) => {
    window.location.href = "/";
  });
}

CodePudding user response:

Creating a handleSubmit function which gets called from the forms onSubmit='handleSubmit()'.

The form information is acquired via: Object.fromEntries((new FormData(event.target)).entries());. which is of the type object.

    function handleSubmit() {
        let formValues = Object.fromEntries((new FormData(event.target)).entries());
        /* call any function you want! */
    }
      <form action="/action_page.php" onsubmit="handleSubmit()">
        Enter name: <input type="text" name="fname"/>
        <input type="submit" value="Submit"/>
      </form> 

-------- EDITED I. Following the recommendation by: isherwood, your result should look something like this:

      function logSubmit(event) {  
        let fieldValue = form.fname.value; //gets field value
        event.preventDefault();
      }

      const form = document.getElementById('form');
      form.addEventListener('submit', logSubmit);
      <form id="form">
        <label>Test field: <input type="text" name="fname"></label>
        <br/><br/>
        <button type="submit">Submit form</button>
      </form>

CodePudding user response:

In HTML there is actually an Event-Listener called "onclick". Try using it on your submit button like this:

<button onclick="uploadFile(file_name, file_data)">Add File</button>
  • Related