Converting an onclick event to onsubmit: Tips for doing it right

Recently, I had to add validation to a file upload form for our Google Drive. After some research, I discovered that using onsubmit instead of onclick was the way to go.

However, when I made the switch from onclick to onsubmit, the validation worked but the file upload function stopped working. Nothing happened when users clicked the submit ("Upload File") button.

The original code looked like this:

<form id="myForm"  >
<center>Please deposit your file using the submission form below.</center>
<br>
<br>
   <font size="3" color="red">*</font>Your Name: <input type="text" name="myName" placeholder="Your name.." required />
   <font size="3" color="red">*</font>Your Email: <small><b>(to contact in case of questions, and send your file deposit receipt)</b></small> <input type="email" name="userMail" placeholder="Your email.." required />
   <br>
   <font size="3" color="red">*</font>File Recipient Name: <input type="text" name="recName" placeholder="Your recipient's name.." required />
   <font size="3" color="red">*</font>File Recipient Email: <small><b>(whom to notify of your deposit)</b></small> <input type="email" name="recEmail" placeholder="Your recipient's email.." required />
   <br>
   School: <small><b>(if your file pertains to a specific school)</b></small> <input type="text" name="aSchool" placeholder="Pertaining school.." /> 
   School Year: <small><b>(if your file pertains to a specific school year)</b></small> <input type="text" name="aSchoolYear" placeholder="Pertaining school year.." />
   <br>
   Note(s): <small><b>(any special note about the file)</b></small> <br> <textarea name="sNote" rows="3" cols="40" > </textarea>
   <br>
   <br>
    <input type="file" name="myFile" required />
    <br>

      <input type="submit" value="Upload File" 
           onclick="this.value='Uploading..';
                    google.script.run.withSuccessHandler(fileUploaded)
                    .uploadFiles(this.parentNode);
                    return false;" />
</form>

My attempt to change onclick to onsubmit resulted in:

<input type="submit" value="Upload File" 
           onsubmit="this.value='Uploading..';
                    google.script.run.withSuccessHandler(fileUploaded)
                    .uploadFiles(this);
                    return false;" />

I'm wondering if there is a better approach to validation while still utilizing onclick. Any suggestions would be greatly appreciated!

Answer №1

Instead of using onsubmit, remember that this refers to the form itself when you change it.

A more efficient approach, in my view, is to utilize JQuery syntax for implementing the event like this:

$(document).on('submit', "#myForm", function(e) {
    var formElement = $(e.currentTarget);
    formElement.find("input[type='submit']").val("Processing..");
    ....
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Error: Attempting to modify a constant variable

Can anyone assist me in resolving this error? I have included my index.js, routes.js, and db.js code along with the error description. I've been putting in a lot of effort to troubleshoot this error. index.js const express = require('express&a ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

Exploring the depths of nested collections in Angular 12

As I work on my very first Angular/Firestore app, I find myself grappling with understanding how to retrieve data from nested collections. The Firestore database path that I need to access is as follows: /Customer(CollectionName)/cl0Apvalb6c0w9hltQ8AOTF4go ...

Different Slide Library Fullpage.js

Is it feasible to have two sections with the same slide in fullpage.js? For example, if I'm currently on slide 1 of section 1 and then move to slide 2 of section 1, can section 2 automatically switch to slide 2 as well? I'm curious if this funct ...

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...

Utilizing external JavaScript libraries in Typescript for integration with nodeJS

We've recently made the switch to using Typescript + Electron for developing a browser-based desktop application. However, we often encounter delays when loading external Javascript libraries. While typings helps with most of our needs, there are stil ...

Determining when all textures have successfully loaded in Three.js and ensuring there are no lingering black rectangles

I'm currently developing a web platform that allows users to customize and preview 3D house models. If the user's browser doesn't support WebGL, the server renders the house and sends screenshots to the client. However, if the screenshots ar ...

Transforming a circular data structure into JSON format within Firebase

The data returned from firebase is causing an issue when I try to stringify it: JSON.stringify(data) // where data represents the returned object This results in the error: TypeError: Converting circular structure to JSON What is the correct way to hand ...

React - Error: you have a syntax problem because there is an unexpected token <

I am working on a project using Express, pg, and react. However, I have encountered some issues with React. Here is the directory of my project index.js var express = require('express'); var server = express(); var path = require('path&ap ...

Typescript error handling: Handle 404s on all Koa routes

Issue Encountering problems while setting up Auth Controllers Difficulty using Bcrypt and JWT for encryption All POST Calls to Koa resulting in 404 errors Calls to other routes are functioning correctly Potential issue with the scope of the code. impo ...

Establish the minimum and maximum values for the text field depending on the selection made in the previous dropdown menu

For my project, I need to create a dropdown menu and a text box positioned next to it. I want the text box to have specific character limits based on the option selected from the dropdown. For example, if "Option 1" is chosen, then the textbox should only ...

Example of a chat server code using NodeJS

I'm looking to add a chat module to my web application. After searching on , I found several chat modules but none of them have clear examples on how to implement them in my project. Can someone share a tutorial that is based on existing NodeJS modul ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

Handling the same form button repeatedly in a loop using jQuery

I have successfully set up jquery to accept form data and send it to flask, but I am facing two issues: It only accepts the first form, which has the same IDs repeated for each element. I want all forms to be able to submit. When a submission occurs, it ...

The edges of the cubemap in THREE.js appear murky

I am attempting to create a black skybox with white dots (stars) in three.js. However, due to the perspective effect, the dots appear darker in the corners where they are further away (as they get smaller and dimmer). Is there a way to make the appearance ...

Populate a secondary dropdown menu using the selection from a primary dropdown menu and retrieve the corresponding "value" instead of displaying the value as a dropdown option

I am attempting to create two dropdowns that are populated by another dropdown. Below is the code: HTML: <form type=get action="action.php"> <select name="meal" id="meal" onChange="changecat(this.value);"> <option value="" disabled select ...

Challenges arise with CSS alignment when adding d3.js charts to a webpage

I'm puzzled by the empty space that appears between the left column (highlighted in the image) and the header. This peculiar gap only seems to occur when the middle column is filled with a chart. I've scrutinized the code using Chrome Developer t ...

Directive not working on Mozilla Firefox

Currently, I have a directive set up to display an image as a background image. This works perfectly fine in Chrome and Safari, but for some reason, it doesn't seem to be functioning properly in Firefox as the background images are not showing up. Aft ...