HTML Form – Input Type and Submit Button Example

Kolade Chris

Forms are one of the most important parts of the web. Without them, there wouldn’t be an easy way to collect data, search for resources, or sign up to receive valuable information.
You can embed forms on websites with the HTML form element. Inside the form element, several inputs are nested. These inputs are also known as form controls.
In this tutorial, we will explore the HTML form element, the various input types it takes, and how to create a submit button with which data is submitted.
By the end, you will know how forms work and you’ll be able to make them with confidence.
Basic HTML Form Syntax
HTML Form Input Types
You use the <input> tag to create various form controls in HTML. It is an inline element and takes attributes such as type , name , minlength , maxlength , placeholder , and so on. Each of these has specific values they take.
The placeholder attribute is important as it helps the user understand the purpose of the input field before they type anything in.
There are 20 different input types, and we will look at them one by one.
Type Text
This type of input takes a value of “text”, so it creates a single line of text input.

An input with the type of text looks like the screenshot below:
Type Password
As the name implies, an input with a type of password creates a password. It is automatically invisible to the user, unless it is manipulated by JavaScript.

Type Email
Any input with the type of email defines a field for entering an email address.

Type Number
This type of input lets the user insert numbers only.

Type Radio
Sometimes, users will need to pick one out of numerous options. An input field with its type attributes set to “radio” lets you do this.

Type Checkbox
So, with an input type of radio, users will be allowed to pick one out of numerous options. What if you want them to pick as many options as possible? That’s what an input with a type attribute set to checkbox does.

Type Submit
You use this type to add a submit button to forms. When a user clicks it, it automatically submits the form. It takes a value attribute, which defines the text that appears inside the button.

Type Button
An input with a type set to button creates a button, which can be manipulated by JavaScript’s onClick event listener type. It creates a button just like an input type of submit, but with the exception that the value is empty by default, so it has to be specified.
Type File
This defines a field for file submission. When a user clicks it, they are prompted to insert the desired file type, which might be an image, PDF, document file, and so on.
The result of an input type of file looks like this:

Type Color
This is a fancy input type introduced by HTML5. With it, the user can submit their favourite color for example. Black (#000000) is the default value, but can be overridden by setting the value to a desired color.
Many developers have used it as a trick to get to select different color shades available in RGB, HSL and alphanumeric formats.
This is the result of an input type of color:

Type Search
Input with the type of search defines a text field just like an input type of text. But this time it has the sole purpose of searching for info. It is different from type text in that, a cancel button appears once the user starts typing.

Type URL
When the type attribute of an input tag is set to URL, it displays a field where users can enter a URL.

Type Tel
An input type of tel lets you collect telephone numbers from users.

Type Date
You might have registered on a website where you requested the date of a certain event. The site probably used an input with the type value set to date to acheive this.
This is what an input with type date looks like:

Type Datetime-local
This works like the input type date, but it also lets the user pick a date with a particular time.

Type Week
The input type of week lets a user select a specific week.

Type Month
The input with the type of month populates months for the user to pick from when clicked.

Textarea
There are times when a user will need to fill in multiple lines of text which wouldn’t be suitable in an input type of text (as it specifies a one-line text field).
textarea lets the user do this as it defines multiple lines of text input. It takes its own attributes such as cols – for the number of columns, and rows for the number of rows.

Multiple Select Box
This is like a radio button and checkbox in one package. It is embedded in the page with two elements – a select element and an option , which is always nested inside select .
By default, the user can only pick one of the options. But with multiple attributes, you can let the user select more than one of the options.
How to Label HTML Inputs
Assigning labels to form controls is important. When they’re properly connected to the input field through their for attribute and the input’s id attribute, it’s easier for the user to use as they can just click the label itself to access the input.
How HTML Forms Work
When a user fills in a form and submits it with the submit button, the data in the form controls are sent to the server through GET or POST HTTP request methods.
So how is the server indicated? The form element takes an action attribute, which must have its value specified to the URL of the server. It also takes a method attribute, where the HTTP method it uses to convey the values to the server is specified.
This method could be GET or POST . With the GET method, the values entered by the user are visible in the URL when the data is submitted. But with POST , the values are sent in HTTP headers, so those values are not visible in the URL.
If a method attribute is not used in the form, it is automatically assumed that the user wants to use the GET method, because it’s the default.
So when should you use the GET or POST method? Use the GET method for submitting non-sensitive data or retrieving data from a server (for example, during searches). Use the POST request when submitting files or sensitive data.
Mini Project: Build a Basic Contact Form
Let’s take what we’ve learned about forms and use it to make a simple contact form. I will also introduce a few new concepts as we go to round it all out.
Here’s the HTML:
What’s going on in this HTML code?
First, a form element is wrapping every other element. It has an action set to “example-server.com”, a dummy server where the form data will be received.
After the form element, every other element is also surrounded by a fieldset element with a legend tag right under it.
We use the fieldset element to group related inputs together, and the legend tag contains a caption conveying what the form is about.
The inputs name , email , and textarea are all in a div with a class of form-control. So they behave like a block element, in order to make styling easier with CSS.
They are also validated with the required attribute, so the form fails to submit when those fields are empty or when the user fails to type in the values in the appropriate format.

After all that, we’ll have the result in the screenshot below:
How ugly is that? We need to apply some styling!
Here’s the CSS:
What’s the CSS code doing here?
We center everything in the body horizontally with Flexbox, and vertically with a 100% viewport height. We used a font-family of cursive.
We gave the inputs and textarea a width of 100% so they go all the way across. The labels got a minimal line-height of 1.9rem (30.4px), so they don’t stay too close to their respective inputs.
We specifically styled the button (input type button) with the transform property to push it to the center as it was off center a bit. We gave it a padding of 3px for more spacing around it. We then selected a cursive font-family for it with a weight of bold.
Because the button was too close to the textarea , we set a margin-top of 0.6rem to push it down a little bit.
We gave our fieldset element a padding of 20px at the top and bottom, with 40px at the left and right to push apart the border it creates around the form elements it is wrapped in.

At the end of it all, we have the beautiful form below:
Conclusion
I hope this tutorial has helped you understand how forms work. Now you should have the knowledge you need to integrate forms into your websites so you can start collecting data.
<input type="submit">
<input> elements of type submit are rendered as buttons. When the click event occurs (typically because the user clicked the button), the user agent attempts to submit the form to the server.
Value
An <input type=»submit»> element’s value attribute contains a string which is displayed as the button’s label. Buttons do not have a true value otherwise.
Setting the value attribute
Omitting the value attribute
If you don’t specify a value , the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of «Submit» or «Submit Query.» Here’s an example of a submit button with a default label in your browser:
Additional attributes
In addition to the attributes shared by all <input> elements, submit button inputs support the following attributes.
formaction
A string indicating the URL to which to submit the data. This takes precedence over the action attribute on the <form> element that owns the <input> .
This attribute is also available on <input type=»image»> and <button> elements.
formenctype
A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values:
This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as encodeURI() .
Uses the FormData API to manage the data, allowing for files to be submitted to the server. You must use this encoding type if your form includes any <input> elements of type file ( <input type=»file»> ).
Plain text; mostly useful only for debugging, so you can easily see the data that’s to be submitted.
If specified, the value of the formenctype attribute overrides the owning form’s action attribute.
This attribute is also available on <input type=»image»> and <button> elements.
formmethod
A string indicating the HTTP method to use when submitting the form’s data; this value overrides any method attribute given on the owning form. Permitted values are:
A URL is constructed by starting with the URL given by the formaction or action attribute, appending a question mark («?») character, then appending the form’s data, encoded as described by formenctype or the form’s enctype attribute. This URL is then sent to the server using an HTTP get request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value.
The form’s data is included in the body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post method. This method supports complex data and file attachments.
This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all.
This attribute is also available on <input type=»image»> and <button> elements.
formnovalidate
A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the novalidate attribute on the element’s owning form.
This attribute is also available on <input type=»image»> and <button> elements.
formtarget
A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a browsing context (that is, a tab, window, or <iframe> ). A value specified here overrides any target given by the target attribute on the <form> that owns this input.
In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used:
Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified.
Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.
Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as _self .
Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as _self .
This attribute is also available on <input type=»image»> and <button> elements.
Using submit buttons
<input type=»submit»> buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use <input type=»button»> , or better still, a <button> element.
If you choose to use <button> elements to create the buttons in your form, keep this in mind: If the <button> is inside a <form> , that button will be treated as the «submit» button. So you should be in the habit of expressly specifying which button is the submit button.
A simple submit button
We’ll begin by creating a form with a simple submit button:
This renders like so:
Try entering some text into the text field, and then submitting the form.
Upon submitting, the data name/value pair gets sent to the server. In this instance, the string will be text=usertext , where «usertext» is the text entered by the user, encoded to preserve special characters. Where and how the data is submitted depends on the configuration of the <form> ; see Sending form data for more details.
Adding a keyboard shortcut to a submit button
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 submit button — just as you would with any <input> 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). In order to avoid conflicts with the user agent’s own keyboard shortcuts, different modifier keys are used for access keys than for other shortcuts on the host computer. See accesskey for further details.
Here’s the previous example with the s access key added:
For example, in Firefox for Mac, pressing Control — Option — S triggers the Send button, while Chrome on Windows uses Alt + S .
The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure 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 access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it’s not a complete solution for accessibility purposes.
Disabling and enabling a submit button
To disable a submit button, specify the disabled attribute on it, like so:
You can enable and disable buttons at run time by setting disabled to true or false ; in JavaScript this looks like btn.disabled = true or btn.disabled = false .
Note: See the <input type=»button»> page for more ideas about enabling and disabling buttons.
Validation
Submit buttons don’t participate in constraint validation; they have no real value to be constrained.
Examples
We’ve included simple examples above. There isn’t really anything more to say about submit buttons. There’s a reason this kind of control is sometimes called a «simple button.»
<input type="submit">
<input> elements of type «submit» are rendered as submit buttons — clicking one will attempt to submit the form to the sever.
| Value | A DOMString used as the button’s label |
| Events | click |
| Supported common attributes | type , and value |
| IDL attributes | value |
| Methods | None |
Value
An <input type=»submit»> elements’ value attribute contains a DOMString that is used as the button’s label.
If you don’t specify a value , you get an button with a default label like Submit/Submit Query (depending on the browser):
Using submit buttons
<input type=»submit»> buttons are used to submit forms. If you want to create a custom button and then customize the behaviour using JavaScript, you need to use <input type=»button»> , or better still, a <button> element.
You do however need to bear in mind that if you only include a single button element inside a form (e.g. <button>My button</button> ), the browser will count this as the submit button. You need to explicitly declare a submit button in addition to any other buttons you may want to include.
A simple submit button
We’ll begin by creating a simple submit button:
This renders like so:
Try entering some text into the text field, and then submitting the form.
Upon submitting, the data name/value pair sent to the server in this case will be along the lines of text=mytext , depending on what text you entered into the text field. Where and how the data is submitted depends on how you set the <form> attributes (and other details) up — see Sending form data for more details.
Adding a submit keyboard shortcut
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 submit button — just as you would with any <input> 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).
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 intefere 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 submit button
To disable a submit button, simply specify the disabled global attribute on it, like so:
You can enable and disable buttons at run time by simply setting disabled to true or false ; in JavaScript this looks like btn.disabled = true .
Note: See the <input type=»button»> page for more ideas about enabling/disabling buttons.
Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads. Use the autocomplete attribute to control this feature.
Validation
Submit buttons don’t participate in constraint validation; they have no real value to be constrained.
Examples
We’ve included simple examples above. There isn’t really anything more to say about submit buttons.
<input type=»submit»>
<input> Элементы <input> типа submit отображаются как кнопки. Когдапроисходит событие click (обычно из-за того, что пользователь нажал кнопку), пользовательский агент пытается отправить форму на сервер.
Value
Атрибут value элемента <input type=»submit»> содержит строку, которая отображается как метка кнопки. В противном случае кнопки не имеют истинного значения. value
Установка атрибута значения
Опуская атрибут значения
Если вы не укажете value , кнопка будет иметь метку по умолчанию, выбранную пользовательским агентом. Этот ярлык, вероятно, будет чем-то вроде «Отправить» или «Отправить запрос». Вот пример кнопки отправки с меткой по умолчанию в вашем браузере:
Additional attributes
Помимо атрибутов, общих для всех элементов <input> , входные данные кнопки submit поддерживают следующие атрибуты.
formaction
Строка, указывающая URL-адрес для отправки данных. Это имеет приоритет над атрибутом action в элементе <form> , которому принадлежит <input> .
Этот атрибут также доступен для элементов <input type=»image»> и <button> .
formenctype
Строка,определяющая метод кодирования при отправке данных формы на сервер.Существует три допустимых значения:
Это значение по умолчанию отправляет данные формы в виде строки после URL-кодирования текста с использованием такого алгоритма, как encodeURI() .
Использует FormData API для управления данными, что позволяет отправлять файлы на сервер. Вы должны использовать этот тип кодировки, если ваша форма включает какие -либо элементы <input> type file ( <input type=»file»> ).
Обычный текст;в основном полезен только для отладки,так что вы можете легко увидеть данные,которые должны быть представлены.
Если указано, значение formenctype атрибута переопределяет форму , владеющей в action атрибут.
Этот атрибут также доступен для элементов <input type=»image»> и <button> .
formmethod
Строка, указывающая метод HTTP для использования при отправке данных формы; это значение переопределяет любой атрибут method указанный в форме-владельце. Допустимые значения:
URL-адрес создается, начиная с URL-адреса, заданного formaction или action , добавляя знак вопроса («?»), А затем добавляя данные формы, закодированные, как описано с помощью formenctype или атрибута enctype формы . Затем этот URL-адрес отправляется на сервер с помощью HTTP- запроса на get . Этот метод хорошо работает для простых форм, содержащих только символы ASCII и не имеющих побочных эффектов. Это значение по умолчанию.
Данные формы включаются в тело запроса, который отправляется на URL-адрес, указанный в formaction или action , с использованием метода HTTP post . Этот метод поддерживает сложные данные и вложения файлов.
Этот метод используется для указания,что кнопка закрывает диалог,с которым связан ввод,и вообще не передает данные формы.
Этот атрибут также доступен для элементов <input type=»image»> и <button> .
formnovalidate
Логический атрибут, который, если он присутствует, указывает, что форма не должна проверяться перед отправкой на сервер. Это отменяет значение атрибута novalidate в форме владельца элемента.
Этот атрибут также доступен для элементов <input type=»image»> и <button> .
formtarget
Строка, указывающая имя или ключевое слово, указывающее, где отображать ответ, полученный после отправки формы. Строка должна быть именем контекста просмотра (то есть вкладки, окна или <iframe> . Указанное здесь значение переопределяет любую цель, заданную target атрибутом в <form> , которая владеет этим вводом.
В дополнение к реальным названиям вкладок,окон или встроенных рамок,есть несколько специальных ключевых слов,которые могут быть использованы:
Загружает ответ в тот же контекст просмотра,что и тот,который содержит форму.Это заменит текущий документ полученными данными.Это значение используется по умолчанию,если не указано ни одного.
Загружает ответ в новый безымянный контекст просмотра. Обычно это новая вкладка в том же окне, что и текущий документ, но она может отличаться в зависимости от конфигурации пользовательского агента .
Загружает ответ в родительский контекст просмотра текущего. Если родительский контекст отсутствует, он ведет себя так же, как _self .
Загружает ответ в контекст просмотра верхнего уровня; это контекст просмотра, который является самым верхним предком текущего контекста. Если текущий контекст является самым верхним контекстом, он ведет себя так же, как _self .
Этот атрибут также доступен для элементов <input type=»image»> и <button> .
Использование кнопок отправки
<input type=»submit»> Кнопки <input type = «submit»> используются для отправки форм. Если вы хотите создать пользовательскую кнопку, а затем настроить ее поведение с помощью JavaScript, вам необходимо использовать <input type=»button»> или, что еще лучше, элемент <button> .
Если вы решите использовать элементы <button> для создания кнопок в вашей форме, имейте это в виду: если внутри <form> есть только один <button> > , эта кнопка будет рассматриваться как кнопка «отправить». Таким образом, вы должны иметь привычку явно указывать, какая кнопка является кнопкой отправки.
Простая кнопка отправки
Начнем с создания формы с простой кнопкой отправки:
Это выглядит так:
Попробуйте ввести некоторый текст в текстовое поле,а затем отправить форму.
После отправки пара имя / значение данных отправляется на сервер. В этом случае строка будет иметь вид text=usertext , где «usertext» — это текст, введенный пользователем, закодированный для сохранения специальных символов. Куда и как будут отправлены данные, зависит от конфигурации <form> ; см. « Отправка данных формы» для получения более подробной информации.
Добавление сочетания клавиш отправки
Сочетания клавиш, также известные как клавиши доступа и их эквиваленты, позволяют пользователю активировать кнопку с помощью клавиши или комбинации клавиш на клавиатуре. Чтобы добавить сочетание клавиш к кнопке отправки — так же, как и к любому <input> , для которого это имеет смысл, — вы используете глобальный атрибут accesskey .
В этом примере, s указывается в качестве клавиши доступа (необходимо нажать кнопку s плюс специальные клавиши-модификаторы для комбинации браузера/ОС. Чтобы избежать конфликтов с собственными сочетаниями клавиш пользовательского агента, для клавиш доступа используются разные клавиши-модификаторы, чем для других сочетаний клавиш на главном компьютере. См. accesskey для получения дополнительной информации.
Вот предыдущий пример с s добавлен ключ доступа:
Например,в Firefox для Mac,нажав кнопку Control — Option — S запускает кнопку Отправить,в то время как Chrome на Windows использует Alt + S .
Проблема с приведенным выше примером заключается в том, что пользователь не будет знать, что такое ключ доступа! Это особенно верно, поскольку модификаторы обычно нестандартны, чтобы избежать конфликтов. При создании сайта не забудьте предоставить эту информацию таким образом, чтобы она не мешала дизайну сайта (например, предоставив легкодоступную ссылку, указывающую на информацию о ключах доступа к сайту). Добавление всплывающей подсказки к кнопке (используя атрибут title ) также может помочь, хотя это не полное решение для целей доступности.
Отключение и включение кнопки отправки
Чтобы отключить кнопку отправки, укажите для нее атрибут disabled ,например:
Вы можете включать и отключать кнопки во время выполнения, установив для disabled значение true или false ; в JavaScript это выглядит как btn.disabled = true или btn.disabled = false .
Примечание. Дополнительные сведения о включении и отключении кнопок см. На странице <input type=»button»> .
Validation
Кнопки отправки не участвуют в валидации ограничений;они не имеют реального значения,которое можно было бы ограничить.
Examples
Мы включили простые примеры выше.Больше нечего сказать о кнопках отправки.Есть причина,по которой такой вид управления иногда называют «простой кнопкой».