Home > Mobile >  How to call Javascript function with HTML button?
How to call Javascript function 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.

<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 App() {

    function handleSubmit() {
        let formValues = Object.fromEntries((new FormData(event.target)).entries());
    
    /* call any function you want! */
    }

    return (
    <>
      <form action="/action_page.php" onsubmit="handleSubmit()">
        Enter name: <input type="text" name="fname"/>
        <input type="submit" value="Submit"/>
      </form>
    </>);
    }
    
    export default App;

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