Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Interrupting form submission with onsubmit

From: Validating and Processing Forms with JavaScript and PHP

Video: Interrupting form submission with onsubmit

When the user submits the form, the browser fires an onsubmit event. Your page can capture that event and prevent the form from being submitted. That way, you can form your own validation, and if necessary add HTML5 functionality to older browsers. So let's see how we can add something like this our form. Here's our form so far. Right now, if I try to send this form, the HTML5 validation will take over. I need to make that work for older browsers. To do that, I'm going to go into my form, and in my HTML document, I'm going to remove the required attributes from both the name as well as the email fields.

Interrupting form submission with onsubmit

When the user submits the form, the browser fires an onsubmit event. Your page can capture that event and prevent the form from being submitted. That way, you can form your own validation, and if necessary add HTML5 functionality to older browsers. So let's see how we can add something like this our form. Here's our form so far. Right now, if I try to send this form, the HTML5 validation will take over. I need to make that work for older browsers. To do that, I'm going to go into my form, and in my HTML document, I'm going to remove the required attributes from both the name as well as the email fields.

We'll add them back later, but that'll make the form work like an older browser. So to prevent a form from submitting, we need to add an onsubmit event handler. Let's do that in our JavaScript file. So, I'm going to go over here, and right after my validation info object, I'm going to add an onsubmit event handler. This is going to be a function literal, which means just a function with no name. And I'm going to put an alert. This is going to say that the submission has been interrupted. And then I'm going to type in return false.

Return false is what's going to prevent the form from submitting. So I'm going to hit Save, go back into my form, refresh. And I'm going to hit the Send button now. And you'll see that the alert comes up, and the form doesn't submit. So even if I type in something in here, hit send. The alert comes up, the form does not submit. My info's still there. So that's all well and good, but we need to add the HTML5 required field functionality into this form for older browsers. So I'll switch back into my script, and I'm going to modify the validation info object.

Right now, it has two fields, my name and my telephone. And the field that I want to modify first is the myName field. I'm going to add a required object here, and I'm going to set this to true. That way, it'll make sure that I validate that field. I'm also going to add a myEmail object here, and set the required field here to true as well. So now that I've done that, I can work on my onsubmit function. I'm going to move the myError variable, which right now is in the input field validation, to the very top, so it's a variable that's accessible to both of our functions.

So I'm going to cut it out of here, and I'm going to put it right up here, next to input fields. So when somebody submits the form, I want to go through all of the elements in my validation info object. And check to see if there's any fields that are required. In this case, my name and my email. So I'll use the for loop, and check for key in validation info. And here, I'm going to create a variable called myField. And that variable is going to be set to the document. And get element by ID.

Then I'll use the key from this for loop here. That'll go through each one of the individual objects in my validation info object. Next, I'm going to check to see if the current validation object has a required element. And also, if my current field, the one that I'm testing, is false or true. So, if the validation objects' key, the current key as we go through this loop, has a required field. And if there is an element, which we stored into this variable called myField. And that element has a value that's empty, then I'm going to do the following.

I'm going to set the error message for the page, I've already done that down here, so I'm just going to copy this line, and paste it right here. And I will change that error to read required field. Then I'll use the key, which the name of the input field, and then I'll add not filled. To help out the user, I'll position the insertion point in whichever field I'm talking about. You could do that with the select method.

And then we'll return false, because we don't want the form to process. If none of the required fields are empty, then I'm going to return true. And the form will submit as usual. Looking at this code, it looks like I need to make sure that I add a double equal sign instead of a single equal. A double equal is a comparison operator. A single equal is an assignment operator. So that needs to be done like that. And I'm going to save this, and I'll switch back onto my form. Refresh it, and I'm going to try to submit the form, and it's going to give me an error right here.

If I do fill out this field, and I try to submit, it'll tell me that the email was not filled, and it'll put the cursor at that spot. So that's working pretty well. Now, I need to go ahead and turn on HTML5 validation for this form, and then use modernizr to make sure that this is going to work in older browsers. So, I'll switch back onto my form, and right over here, I'm going to add an if statement. And what I need to check is that if the modernizr object does not have the required variable in it, then it's going to perform everything in here.

So I'm going to place all this code in there, indent things a little bit, and I'll add another comma in, right here. I need to go back into my HTML, and make sure I add the required attributes. Now, if I go back into my form and refresh, the HTML5 validation will take over in this browser, and browsers that do not support the required attribute will be handled by my JavaScript. Sometimes its better for validation to happen as the user interacts for your form.

By capturing the onsubmit event, we can perform our own validation, and also make up for some of the missing HTML5 attributes in older browsers.

Show transcript

This video is part of

Image for Validating and Processing Forms with JavaScript and PHP
 
Expand all | Collapse all
  1. 3m 36s
    1. Welcome
      1m 9s
    2. What you should know
      1m 2s
    3. Using the exercise files
      1m 25s
  2. 12m 50s
    1. Understanding forms
      2m 2s
    2. Working with form fields
      7m 4s
    3. Using the form tag
      3m 44s
  3. 19m 23s
    1. Using input validation
      2m 10s
    2. Adding required fields and placeholders
      1m 31s
    3. Constraining numeric and date fields
      2m 32s
    4. Accepting multiple entries
      1m 41s
    5. Limiting uploads by MIME types
      2m 35s
    6. Assisting text input with a datalist
      1m 55s
    7. Constraining with regular expression patterns
      6m 59s
  4. 42m 13s
    1. Accessing forms
      3m 57s
    2. Looking up form elements
      3m 35s
    3. Handling focus changes
      2m 47s
    4. Detecting the onchange event
      4m 31s
    5. Using the selectedIndex property
      2m 30s
    6. Dynamic validation with regular expressions
      7m 0s
    7. Creating a generic input validation function
      4m 31s
    8. Validating in older browsers with Modernizr
      7m 32s
    9. Interrupting form submission with onsubmit
      5m 50s
  5. 15m 20s
    1. Understanding jQuery
      3m 47s
    2. Validating on submit with jQuery
      3m 45s
    3. Building interactive jQuery validation
      2m 34s
    4. Using the jQuery Validation plugin
      5m 14s
  6. 32m 57s
    1. Communicating with PHP servers
      2m 27s
    2. Retrieving data from superglobals
      8m 18s
    3. Using server-side validation
      4m 59s
    4. Adding in-page validation
      5m 22s
    5. Mirroring input data back to the user
      7m 46s
    6. Sanitizing form input
      4m 5s
  7. 43m 29s
    1. Mailing form data
      8m 28s
    2. Understanding file uploads
      3m 1s
    3. Uploading files
      9m 20s
    4. Processing form data with AJAX
      8m 14s
    5. Preparing your database
      5m 50s
    6. Pushing data
      8m 36s
  8. 1m 17s
    1. Next steps
      1m 17s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Validating and Processing Forms with JavaScript and PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.