Javascript submit form with values

Forms: event and method submit

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript.

The method form.submit() allows to initiate form sending from JavaScript. We can use it to dynamically create and send our own forms to server.

Let’s see more details of them.

Event: submit

There are two main ways to submit a form:

Both actions lead to submit event on the form. The handler can check the data, and if there are errors, show them and call event.preventDefault() , then the form won’t be sent to the server.

Both actions show alert and the form is not sent anywhere due to return false :

 First: Enter in the input field  
Second: Click "submit":

When a form is sent using Enter on an input field, a click event triggers on the .

That’s rather funny, because there was no click at all.

Method: submit

To submit a form to the server manually, we can call form.submit() .

Then the submit event is not generated. It is assumed that if the programmer calls form.submit() , then the script already did all related processing.

Sometimes that’s used to manually create and send a form, like this:

let form = document.createElement('form'); form.action = 'https://google.com/search'; form.method = 'GET'; form.innerHTML = ''; // the form must be in the document to submit it document.body.append(form); form.submit();

Tasks

Create a function showPrompt(html, callback) that shows a form with the message html , an input field and buttons OK/CANCEL .

  • A user should type something into a text field and press Enter or the OK button, then callback(value) is called with the value they entered.
  • Otherwise if the user presses Esc or CANCEL, then callback(null) is called.

In both cases that ends the input process and removes the form.

  • The form should be in the center of the window.
  • The form is modal. In other words, no interaction with the rest of the page is possible until the user closes it.
  • When the form is shown, the focus should be inside the for the user.
  • Keys Tab / Shift + Tab should shift the focus between form fields, don’t allow it to leave for other page elements.
showPrompt("Enter something
. smart :)", function(value) < alert(value); >);

P.S. The source document has HTML/CSS for the form with fixed positioning, but it’s up to you to make it modal.

A modal window can be implemented using a half-transparent that covers the whole window, like this:

Because the covers everything, it gets all clicks, not the page below it.

Also we can prevent page scroll by setting body.style.overflowY=’hidden’ .

The form should be not in the , but next to it, because we don’t want it to have opacity .

Comments

  • If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
  • If you can’t understand something in the article – please elaborate.
  • To insert few words of code, use the tag, for several lines – wrap them in tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)

Источник

How to Submit a Form with JavaScript – JS Submit Button Example

Joel Olawanle

Joel Olawanle

How to Submit a Form with JavaScript – JS Submit Button Example

When building applications and websites on the internet, you’ll sometimes need your users to supply information by filling out a form.

But then you might wonder – how do you get this data from the form? Well, you can do this with JavaScript.

In this article, you will learn how to create a form and get data from it when the form is submitted with JavaScript.

This article won’t cover how to input data into a database – it will only cover how to submit a form. But you should know that once you have this data, you can send it to the database of your choice, use it to manipulate information, and much more.

To submit a form using JavaScript, you must first create the form and add distinctive, specific attributes to the input fields. You will use these attributes to retrieve the data when the user submits and then calls a function to handle validations (possibly if any data is submitted).

How to Create the HTML Form

To get started, let’s create a basic HTML form with two fields: username and password. We’ll also add a button that will be used to submit the form and trigger a JavaScript action.

To get this form’s data via JavaScript, you’ll need to attach specific attributes to the form input field and the form itself. These attributes can be an id , a class , or even with the name tag. This will help get the data in JavaScript using their document methods.

For example, if you use an id attribute on your input field, you can access the input field data and other values using the document method getElementByID(‘idName’) :

// HTML // JS let myUsername = document.getElementById('username'); console.log(myUsername); 

If you use a class attribute, you’ll use getElementsByClassName(className) , which returns an array of all elements with the className . If it is only one element, you can use the index number 0 to access its data:

// HTML // JS let myUsername = document.getElementsByClassName('username'); console.log(myUsername[0]); 

If you use the name attribute, you’ll use getElementsByName(name) . This is similar to how the class attribute works since it also returns an array which you can loop through or access with its index number:

// HTML // JS let myUsername = document.getElementsByName('username'); console.log(myUsername[0]); 

Note: This will not return the input value but the input element itself.

How to Submit a Form with JavaScript

The first step is to attach your preferred attribute to the form, which you can use to track when the form is submitted. This can be an id , class or name attribute, but for this article, I will use id for the form and input fields:

At this point, you can now handle form submission with JavaScript. You first get the form with your preferred attribute, which can be an id, and store it in a variable:

let loginForm = document.getElementById("loginForm"); 

Then you can attach the addEventListener to the form variable and listen for a submit event. This event listener allows you to attach a callback function which gets triggered once the form is submitted:

loginForm.addEventListener("submit", (e) => < e.preventDefault(); // handle submit >); 

At this point, you can now get the form data and handle any operation you wish. For this article, let’s first validate the data by checking if the input is empty before performing any operation:

loginForm.addEventListener("submit", (e) => < e.preventDefault(); let username = document.getElementById("username"); let password = document.getElementById("password"); if (username.value == "" || password.value == "") < // throw error >else < // perform operation with form input >>); 

This is the entire JavaScript code:

let loginForm = document.getElementById("loginForm"); loginForm.addEventListener("submit", (e) => < e.preventDefault(); let username = document.getElementById("username"); let password = document.getElementById("password"); if (username.value == "" || password.value == "") < alert("Ensure you input a value in both fields!"); >else < // perform operation with form input alert("This form has been successfully submitted!"); console.log( `This form has a username of $and password of $` ); username.value = ""; password.value = ""; > >); 

Conclusion

In this article, you have learned how to submit a form with JavaScript and how it works with the various DOM methods.

There are other ways you can do this, but this is a straightforward way to handle submission in JavaScript.

You can access over 150 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.

Источник

Читайте также:  All spider man games java
Оцените статью