• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

165
Views
How to call Javascript function and pass elements with HTML button?

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 = "/";
  });
}
about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>
about 3 years ago · Juan Pablo Isaza Report

0

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>
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error