- How to Submit a Form with JavaScript – JS Submit Button Example
- How to Create the HTML Form
- How to Submit a Form with JavaScript
- Conclusion
- Html form button script
- Button without a value
- Using buttons
- A simple button
- Adding keyboard shortcuts to buttons
- Disabling and enabling a button
- Setting the disabled attribute
- Inheriting the disabled state
- Validation
- Examples
- Technical summary
- Specifications
- Html form button script
How to Submit a Form with JavaScript – JS Submit Button Example
Joel Olawanle
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.
Html form button script
An elements’ value attribute contains a string that is used as the button’s label.
input type="button" value="Click Me" />
Button without a value
If you don’t specify a value , you get an empty button:
Using buttons
A simple button
We’ll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph):
form> input type="button" value="Start machine" /> form> p>The machine is stopped.p>
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() if (button.value === "Start machine") button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > >
The script gets a reference to the HTMLInputElement object representing the in the DOM, saving this reference in the variable button . addEventListener() is then used to establish a function that will be run when click events occur on the button.
Adding keyboard shortcuts to buttons
Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any for which it makes sense — you use the accesskey global attribute.
In this example, s is specified as the access key (you’ll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).
form> input type="button" value="Start machine" accesskey="s" /> form> p>The machine is stopped.p>
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() if (button.value === "Start machine") button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > >
Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you’d have to provide this information in a way that doesn’t interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).
Disabling and enabling a button
To disable a button, specify the disabled global attribute on it, like so:
input type="button" value="Disable me" disabled />
Setting the disabled attribute
You can enable and disable buttons at run time by setting disabled to true or false . In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true . A setTimeout() function is then used to reset the button back to its enabled state after two seconds.
input type="button" value="Enabled" />
const button = document.querySelector("input"); button.addEventListener("click", disableButton); function disableButton() button.disabled = true; button.value = "Disabled"; setTimeout(() => button.disabled = false; button.value = "Enabled"; >, 2000); >
Inheriting the disabled state
If the disabled attribute isn’t specified, the button inherits its disabled state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a element, and then setting disabled on the container.
The example below shows this in action. This is very similar to the previous example, except that the disabled attribute is set on the when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.
fieldset> legend>Button grouplegend> input type="button" value="Button 1" /> input type="button" value="Button 2" /> input type="button" value="Button 3" /> fieldset>
const button = document.querySelector("input"); const fieldset = document.querySelector("fieldset"); button.addEventListener("click", disableButton); function disableButton() fieldset.disabled = true; setTimeout(() => fieldset.disabled = false; >, 2000); >
Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the autocomplete attribute to control this feature.
Validation
Buttons don’t participate in constraint validation; they have no real value to be constrained.
Examples
div class="toolbar"> input type="color" aria-label="select pen color" /> input type="range" min="2" max="50" value="30" aria-label="select pen size" />span class="output">30span> input type="button" value="Clear canvas" /> div> canvas class="myCanvas"> p>Add suitable fallback here.p> canvas>
body background: #ccc; margin: 0; overflow: hidden; > .toolbar background: #ccc; width: 150px; height: 75px; padding: 5px; > input[type="color"], input[type="button"] width: 90%; margin: 0 auto; display: block; > input[type="range"] width: 70%; > span position: relative; bottom: 5px; >
const canvas = document.querySelector(".myCanvas"); const width = (canvas.width = window.innerWidth); const height = (canvas.height = window.innerHeight - 85); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector(".output"); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees) return (degrees * Math.PI) / 180; > // update sizepicker output value sizePicker.oninput = () => output.textContent = sizePicker.value; >; // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) => curX = e.pageX; curY = e.pageY; >; canvas.onmousedown = () => pressed = true; >; canvas.onmouseup = () => pressed = false; >; clearBtn.onclick = () => ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); >; function draw() if (pressed) ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc( curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false, ); ctx.fill(); > requestAnimationFrame(draw); > draw();
Technical summary
Specifications
Html form button script
Для отправки введенных данных на форме используются кнопки. Для создания кнопки используется либо элемент button :
С точки зрения функциональности в html эти элементы не совсем равноценны, но в данном случае они нас интересуют с точки зрения взаимодействия с кодом javascript.
При нажатии на любой из этих двух вариантов кнопки происходит отправка формы по адресу, который указан у формы в атрибуте action , либо по адресу веб-страницы, если атрибут action не указан. Однако в коде javascript мы можем перехватить отправку, обрабатывая событие click
При нажатии на кнопку происходит событие click , и для его обработки к кнопке прикрепляем обработчик sendForm . В этом обработчике проверяем введенный в текстовое поле текст. Если его длина больше 5 символов, то выводим сообщение о недостимой длине и прерываем обычный ход события с помощью вызова e.preventDefault() . В итоге форма не отправляется.
Если же длина текста меньше шести символов, то также выводится сообщение, и затем форма отправляется.
Также мы можем при необходимости при отправке изменить адрес, на который отправляются данные:
function sendForm(e)< // получаем значение поля key var keyBox = document.search.key; var val = keyBox.value; if(val.length>5) < alert("Недопустимая длина строки"); document.search.action="PostForm"; >else alert("Отправка разрешена"); >
В данном случае, если длина текста больше пяти символов, то текст отправляется, только теперь он отправляется по адресу PostForm , поскольку задано свойство action:
document.search.action="PostForm";
Для очистки формы предназначены следующие равноценные по функциональности кнопки:
При нажатию на кнопки произойдет очистка форм. Но также функциональность по очистке полей формы можно реализовать с помощью метода reset() :
function sendForm(e)< // получаем значение поля key var keyBox = document.search.key; var val = keyBox.value; if(val.length>5) < alert("Недопустимая длина строки"); document.search.reset(); e.preventDefault(); >else alert("Отправка разрешена"); >
Кроме специальных кнопок отправки и очистки на форме также может использоваться обычная кнопка:
При нажатии на подобную кнопку отправки данных не происходит, хотя также генерируется событие click:
При нажатии на кнопку получаем введенный в текстовое поле текст, создаем новый элемент параграфа для этого текста и добавляем параграф в элемент printBlock.