HTML provides a number of elements which can be used together to create forms which the user can fill out and submit to the Web site or application. There's a great deal of further information about this available in the HTML forms guide.
Element | Description |
---|---|
<button> |
The HTML <button> element represents a clickable button, which can be used in forms or anywhere in a document that needs simple, standard button functionality. |
<datalist> |
The HTML <datalist> element contains a set of <option> elements that represent the values available for other controls. |
<fieldset> |
The HTML <fieldset> element is used to group several controls as well as labels (<label> ) within a web form. |
<form> |
The HTML <form> element represents a document section that contains interactive controls for submitting information to a web server. |
<input> |
The HTML <input> element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. |
<label> |
The HTML <label> element represents a caption for an item in a user interface. |
<legend> |
The HTML <legend> element represents a caption for the content of its parent <fieldset> . |
<meter> |
The HTML <meter> element represents either a scalar value within a known range or a fractional value. |
<optgroup> |
The HTML <optgroup> element creates a grouping of options within a <select> element. |
<option> |
The HTML <option> element is used to define an item contained in a <select> , an <optgroup> , or a <datalist> element. As such, <option> can represent menu items in popups and other lists of items in an HTML document. |
<output> |
The HTML Output element (<output> ) is a container element into which a site or app can inject the results of a calculation or the outcome of a user action. |
<progress> |
The HTML <progress> element displays an indicator showing the completion progress of a task, typically displayed as a progress bar. |
<select> |
The HTML <select> element represents a control that provides a menu of options |
<textarea> |
The HTML <textarea> element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form. |
= new in HTML5.
Tag | Description |
---|---|
<form> | Defines an HTML form for user input |
<input> | Defines an input control |
<textarea> | Defines a multiline input control (text area) |
<label> | Defines a label for an <input> element |
<fieldset> | Groups related elements in a form |
<legend> | Defines a caption for a <fieldset> element |
<select> | Defines a drop-down list |
<optgroup> | Defines a group of related options in a drop-down list |
<option> | Defines an option in a drop-down list |
<button> | Defines a clickable button |
<datalist> | Specifies a list of pre-defined options for input controls |
<output> | Defines the result of a calculation |
The readonly attribute specifies that the input field is read only (cannot be changed)
<input type="text" name="firstname" value="John" readonly>
The disabled attribute specifies that the input field is disabled.
A disabled input field is unusable and un-clickable, and its value will not be sent when submitting the form:
<input type="text" name="firstname" value="John" disabled>
The size attribute specifies the size (in characters) for the input field:
<input type="text" name="firstname" value="John" size="40">
The maxlength attribute specifies the maximum allowed length for the input field:
<input type="text" name="firstname" maxlength="10">
HTML5 added the following attributes for <input>:
and the following attributes for <form>:
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off.
The novalidate attribute is a <form> attribute.
When present, novalidate specifies that the form data should not be validated when submitted.
<form action="action.php" novalidate> E-mail: <input type="email" name="user_email"> <input type="submit"> </form>
The autofocus attribute specifies that the input field should automatically get focus when the page loads.
First name:<input type="text" name="fname" autofocus>
The form attribute specifies one or more forms an <input> element belongs to.
Tip: To refer to more than one form, use a space-separated list of form ids.
<form action="action.php" id="form1"> First name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> <p>The "Last name" field below is outside the form element, but still part of the form.</p> Last name: <input type="text" name="lname" form="form1">
The multiple attribute specifies that the user is allowed to enter more than one value in the <input> element.
The multiple attribute works with the following input types: email, and file.
Select images: <input type="file" name="img" multiple>
The pattern attribute specifies a regular expression that the <input> element's value is checked against.
The pattern attribute works with the following input types: text, search, url, tel, email, and password.
Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
The placeholder attribute specifies a hint that describes the expected value of an input field (a sample value or a short description of the format).
The hint is displayed in the input field before the user enters a value.
The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
<input type="text" name="fname" placeholder="First name">
The required attribute specifies that an input field must be filled out before submitting the form.
The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
There are three possibilities for enctype:
Value | Description |
---|---|
application/x-www-form-urlencoded | Default. All characters are encoded before sent (spaces are converted to "+" symbols, and special characters are converted to ASCII HEX values) |
multipart/form-data | This value is necessary if the user will upload a file through the form |
text/plain | Sends data without any encoding at all. Not recommended |
Almost every website that you work on will have a form of some sort on it. While you can access a form or form element directly using getElementById
or another method mentioned above, the best way to access any given form is using the document.forms
syntax, which is basically acessing the "forms" collection of the document object.
For example, look at the following XHTML:
<form id="my_form" method="post" action="form.html"> <input type="checkbox" value="one" name="options" id="option1" checked="checked" /> One<br /> <input type="checkbox" value="two" name="options" id="option2" /> Two<br /> <input type="checkbox" value="three" name="options" id="option3" /> Three<br /> </form>
We could find out the "checked" state of any of the checkboxes with the following code:
var myCheckBoxOne = document.forms["my_form"]["option1"]; alert(myCheckBoxOne.checked);
In the above example, the alert message will display "true", because the checkbox that we're accessing ("option1") has its checked
attribute set. If we change the code to access "option2", the result will be an alert message of "false".
Radio buttons are accessed similarly, but instead of being treated as separate entities (as is usually the case with checkboxes), radio buttons are accessed as one collective object. To find out which radio button in a group is selected, we can use a loop. Take a look at the following XHTML:
<form id="my_form" method="post" action="form.html"> <input type="radio" value="one" name="options" /> One<br /> <input type="radio" value="two" name="options" checked="checked" /> Two<br /> <input type="radio" value="three" name="options" /> Three<br /> </form>
And here is the loop that will alert a message that displays the "value" attribute of the selected radio button:
var radioButtonGroup = document.forms["my_form"]["options"]; for (var i = 0; i < radioButtonGroup.length; i++) { if (radioButtonGroup[i].checked == true) { alert("Your selection is " + radioButtonGroup[i].value); } }
Document forms are members of the special collection document.forms.
That’s a named collection: we can use both the name and the number to get the form.
document.forms.my - the form with name="my" document.forms[0] - the first form in the document
When we have a form, then any element is available in the named collection form.elements
<form name="my"> <input name="one" value="1"> <input name="two" value="2"> </form> <script> // get the form let form = document.forms.my; // <form name="my"> element // get the element let elem = form.elements.one; // <input name="one"> element alert(elem.value); // 1 </script>
There may be multiple elements with the same name, that’s often the case with radio buttons.
In that case form.elements[name] is a collection, for instance:
<form> <nput type="radio" name="age" value="10"> <input type="radio" name="age" value="20"> </form> <script> let form = document.forms[0]; let ageElems = form.elements.age; alert(ageElems[0].value); // 10, the first input value </script>
These navigation properties do not depend on the tag structure. All elements, no matter how deep they are in the form, are available in form.elements.
Find out how many <form> elements there are in the document:
var x = document.forms.length;
Get the id of the first <form> element (index 0) in the document
var x = document.forms[0].id; or var x = document.forms.item(0).id; or var x = document.forms.namedItem("myCarForm").id;
Loop through all <form> elements in the document, and output the id of each form:
<form id="myCarForm"> Favorite Car: <input type="text" name="fname" value="Volvo"> </form> <form id="myColorForm"> Favorite Color: <input type="text" name="favcolor" value="Blue"> </form> <p id="demo"></p> <script> var x = document.forms; var txt = ""; var i; for (i = 0; i < x.length; i++) { txt = txt + x[i].id + "<br>"; } document.getElementById("demo").innerHTML = txt; </script> output: myCarForm myColorForm
There’s a shorter notation: we can access the element as form[index/name] .
Instead of form.elements.login we can write form.login.
That also works, but there’s a minor issue: if we access an element, and then change its name, then it is still available under the old name (as well as under the new one).
That’s easy to see in an example:
<form id="form"> <input name="login"> </form> <script> alert(form.elements.login == form.login); // true, the same <input> form.login.name = "username"; // change the name of the input // form.elements updated the name: alert(form.elements.login); // undefined alert(form.elements.username); // input // the direct access now can use both names: the new one and the old one alert(form.username == form.login); // true </script>
That’s usually not a problem, because we rarely change names of form elements.
Let’s talk about form controls, pay attention to their specific features.
Normally, we can access the value as input.value or input.checked for checkboxes.
Like this:
input.value = "New value"; textarea.value = "New text"; input.checked = true; // for a checkbox or radio button
Please note that we should never use textarea.innerHTML: it stores only the HTML that was initially on the page, not the current value.
Find out how many elements there are in a specified <form> element:
var x = document.getElementById("myForm").elements.length;
<form id="myForm"> First name: <input type="text" name="fname" value="Donald"> Last name: <input type="text" name="lname" value="Duck"> <input type="submit" value="Submit"> </form> <script> var x = document.getElementById("myForm").elements[0].value; // Donald </script>
Get the value of the element with name="fname" in a form:
var x = document.getElementById("myForm").elements.namedItem("fname").value; or var x = document.getElementById("myForm").fname.value;
Using theelements
collection together with document.forms to get the value of each element in the form:
<form> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br> City: <input type="text" name="fname" value="Duckburg"><br> <input type="submit" value="Submit"> </form> <p>Click the "Try it" button to display the value of each element in the form.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.forms[0]; var txt = ""; var i; for (i = 0; i < x.length; i++) { txt = txt + x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = txt; } </script> output: Donald Duck Duckburg Submit
A form may have one or many <fieldset> elements inside it. They also support the elements property.
For instance:
<form id="form"> <fieldset name="userFields"> <legend>info</legend> <input name="login" type="text"> </fieldset> </form> <script> alert(form.elements.login); // <input name="login"> let fieldset = form.elements.userFields; alert(fieldset); // HTMLFieldSetElement // we can get the input both from the form and from the fieldset alert(fieldset.elements.login == form.elements.login); // true </script> </body>
For any element, the form is available as element.form. So a form references all elements, and elements reference the form.
Here’s the picture:
<form id="form"> <input type="text" name="login"> </form> <script> // form -> element let login = form.login; // element -> form alert(login.form); // HTMLFormElement </script>
<form id="my-form"> <input type="text" name="username"> <input type="text" name="full-name"> <input type="password" name="password"> </form>
var inputs = document.getElementById("my-form").elements; var inputByIndex = inputs[0]; var inputByName = inputs["username"];
This example gets the form's element list, then iterates over the list, looking for <input> elements of type "text" so that some form of processing can be performed on them.
var inputs = document.getElementById("my-form").elements; // Iterate over the form controls for (i = 0; i < inputs.length; i++) { if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") { // Update text input inputs[i].value.toLocaleUpperCase(); } }
Disabling form controls
var inputs = document.getElementById("my-form").elements; // Iterate over the form controls for (i = 0; i < inputs.length; i++) { // Disable all form controls inputs[i].setAttribute("disabled", ""); }
user_input = document.forms[0].select.value;
To change the selected option in a select box, you have to change its selectedIndex
, like
document.forms[0].select.selectedIndex = 2;
<select name="mySelect"> <option>option 1</option> <option>option 2</option> <option>option 3</option> </select> <script> document.forms[0].mySelect.selectedIndex = 1; // option 2 selected </script>
Checkboxes need a slightly different approach. We already know their values, but want to know whether the user has checked them. The checked property tells us. It can have two values: true or false.
if (document.forms[0].checkbox.checked) { user_input = document.forms[0].checkbox.name }
in which checkbox is the name of the checkbox. If the checkbox is checked, we take its name (or its value, if you need that bit of data) and transfer it to user_input.
To check a checkbox, set its property checked to true:
document.forms[0].checkbox.checked = true
Unfortunately it's not possible to see at once which radio button in a group the user has checked. You need to go through all radio's and see which one's checked property is true.
for (i=0;i<document.forms[0].radios.length;i++) { if (document.forms[0].radios[i].checked) { user_input = document.forms[0].radios[i].value; } }
where radios
is the name of the group of radio buttons.
Note that document.forms[0].radios
is an array filled with all radio buttons. Loop through all of them and see if it is checked. If one is, transfer the value of that radio button to user_input.
To check a radio button, set its property checked to true:
document.forms[0].radios[i].checked = true;
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send()
method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Video Tuts by dcode - Dec 24, 2020
developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
<form id="form1"> <button id="btn1" name="subject" type="submit" value="ok">ok</button> </form> <script> // disable a button document.getElementById("btn1").disabled = true; // find the name of a button var btnName = document.getElementById("btn1").name; aler(btnName); // subject // find the type of a button var btnType = document.getElementById("btn1").type; alert(btnType); // button // find the value of a button var btnValue = document.getElementById("btn1").value; alert(btnValue); // // Find the text displayed on a button var btnTxt = document.getElementById("btn1").innerHTML; alert(btnTxt); // ok // Find the id of the form a button belongs to var btnFormId = document.getElementById("btn1").form.id; alert(btnFormId); // form1 </script>
Reset a form
document.getElementById("form1").reset();
Submit a form
<form id="form1" action="/action_page.php"> First name: <input type="text" name="fname"> Last name: <input type="text" name="lname"> <input type="button" onclick="myFunction()" value="Submit"> </form> <script> function myFunction() { document.getElementById("form1").submit(); } </script>
Find the value of each element in a form
<form id="form1"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br><br> <input type="submit" value="Submit"> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("form1"); var text = ""; var i; for (i = 0; i < x.length ;i++) { text += x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = text; } </script> result: Donald Duck Submit
Find the accepted character set of a form
<form id="frm1" accept-charset="ISO-8859-1"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("frm1").acceptCharset; document.getElementById("demo").innerHTML = x; } </script> result: ISO-8859-1
Find the action attribute of a form
<form id="form1" action="/action_page.php"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br><br> <input type="submit" value="Submit"> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("frm1").action; document.getElementById("demo").innerHTML = x; } </script> result: http://javascript.sibase.co.uk/action_page.php
Find the value of the enctype attribute in a form
<form id="form1" action="/action_page.php" method="post"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br><br> <input type="submit" value="Submit"> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("form1").enctype; document.getElementById("demo").innerHTML = x; } </script> result: application/x-www-form-urlencoded
Find the number of elements in a form
<form id="form1" action="/action_page.php"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br><br> <input type="submit" value="Submit"> </form> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("form1").length; document.getElementById("demo").innerHTML = x; } </script> result: 3
Find the method for sending form data
document.getElementById("form1").method; // get
Find the name of a form
document.getElementById("form1").name;
Find the target of a form
<form id="frm1" action="/action_page.php" target="_self"> // form body </form <script> document.getElementById("frm1").target; // _self </script>
<label for="beans">How many beans can you eat?</label> <input type="range" name="beans" id="beans" min="0" max="500" step="10"> <span class="beancount"></span> <script> var beans = document.querySelector('#beans'); var count = document.querySelector('.beancount'); count.textContent = beans.value; beans.oninput = function() { count.textContent = beans.value; } </script>
Attribute | Value | Description |
---|---|---|
autofocus | autofocus | Specifies that the drop-down list should automatically get focus when the page loads |
disabled | disabled | Specifies that a drop-down list should be disabled |
form | form_id | Defines one or more forms the select field belongs to |
multiple | multiple | Specifies that multiple options can be selected at once |
name | name | Defines a name for the drop-down list |
required | required | Specifies that the user is required to select a value before submitting the form |
size | number | Defines the number of visible options in a drop-down list |
A <select> element has 3 important properties:
So we have three ways to set the value of a <select>:
The first way is the most obvious, but (2) and (3) are usually more convenient.
Here is an example:
<select id="select"> <option value="apple">Apple</option> <option value="pear">Pear</option> <option value="banana">Banana</option> </select> <script> // all three lines do the same thing select.options[2].selected = true; select.selectedIndex = 2; select.value = 'banana'; </script>
Unlike most other controls, <select multiple> allows multiple choice. In that case we need to walk over select.options to get all selected values.
Like this:
<select id="select" multiple> <option value="blues" selected>Blues</option> <option value="rock" selected>Rock</option> <option value="classic">Classic</option> </select> <script> // get all selected values from multi-select let selected = Array.from(select.options) .filter(option => option.selected) .map(option => option.value); alert(selected); // blues,rock </script>
The full specification of the <select> element is available at https://html.spec.whatwg.org/multipage/forms.html#the-select-element.
In the specification of the option element there’s a nice short syntax to create <option> elements:
option = new Option(text, value, defaultSelected, selected);
Parameters:
For instance:
let option = new Option("Text", "value"); // creates <option value="value">Text</option>The same element selected:
let option = new Option("Text", "value", true, true);
Example from javascript.info
<form id="form"> <select id="mySelectId" name="mySelect"> <option value="apple">Apple</option> <option value="pear">Pear</option> <option value="banana">Banana</option> </select> </form> <script> // all three lines do the same thing mySelectId.options[2].selected = true; mySelectId.selectedIndex = 2; mySelectId.value = 'banana'; // we can use formId.selectName.property form.mySelect.options[2].selected = true; alert(form.mySelect[2].value); // banana </script>
Option elements have additional properties:
Disable and enable a dropdown list
<form> <select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="disable()" value="Disable list"> <input type="button" onclick="enable()" value="Enable list"> </form> <script> function disable() { document.getElementById("mySelect").disabled=true; } function enable() { document.getElementById("mySelect").disabled=false; } </script>
Get the total number of dropdown list
document.getElementById("mySelect").length;
Turn the dropdown list into a multiline list
<form> <select id="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option> <option>Melon</option> </select> <input type="button" onclick="changeSize()" value="Change size"> </form> <script> function changeSize() { document.getElementById("mySelect").size = 4; } </script>
Select multiple options in a dropdown list
document.getElementById("mySelect").multiple = true;
Display the selected option in a dropdown list
var obj = document.getElementById("mySelect"); obj.options[obj.selectedIndex].text;
Display all options from a dropdown list
<form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <input type="button" onclick="getOptions()" value="Output all options"> </form> <p id="demo"></p> <script> function getOptions() { var x = document.getElementById("mySelect"); var txt = ""; var i; for (i = 0; i < x.length; i++) { txt = txt + " " + x.options[i].text; } document.getElementById("demo").innerHTML = txt; } </script> output: Apple Orange Pineapple Banana
The selectedIndex property sets or returns the index of the selected option in a drop-down list.
The index starts at 0.
Note: If the drop-down list allows multiple selections it will only return the index of the first option selected.
Note: The value "-1" will deselect all options (if any).
Note: If no option is selected, the selectedIndex property will return -1.
Display the index of the selected option in a dropdown list
document.getElementById("mySelect").selectedIndex;
Change the text of the selected option
<form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br><br> <input type="button" onclick="changeText()" value="Set text of selected option"> </form> <script> function changeText() { x = document.getElementById("mySelect"); x.options[x.selectedIndex].text = "Melon"; } </script>
// x = document.getElementById("mySelect"); // x.options[x.selectedIndex].text = "Melon"; document.getElementById("mySelect").options[document.getElementById("mySelect").selectedIndex].text = "Melon";
Remove options from a dropdown list
<form> <select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="removeOption()" value="Remove the selected option"> </form> <script> function removeOption() { var x = document.getElementById("mySelect"); x.remove(x.selectedIndex); } </script>
// Get all options within <select id='foo'>...</select> var op = document.getElementById("foo").getElementsByTagName("option"); for (var i = 0; i < op.length; i++) { // lowercase comparison for case-insensitivity (op[i].value.toLowerCase() == "stackoverflow") ? op[i].disabled = true : op[i].disabled = false ; }
The add()
method is used to add an option to a drop-down list.
selectObject.add(option, index)
Parameter | Description |
---|---|
option | Required. Specifies the option to add. Must be an option or optgroup element |
index | Optional. An integer that specifies the index position for where the new option element should be inserted. Index starts at 0. If no index is specified, the new option will be inserted at the end of the list |
Add a "Kiwi" option at the end of a drop-down list:
<form> <select id="mySelect" size="8"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> </form> <br> <button type="button" onclick="myFunction()">Insert option</button> <script> function myFunction() { var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option); } </script>
Add a "Kiwi" option at the beginning of a drop-down list:
var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option, x[0]);
Add a "Kiwi" option at index position "2" of a drop-down list:
var x = document.getElementById("mySelect"); var option = document.createElement("option"); option.text = "Kiwi"; x.add(option, x[2]);
Add an option before a selected option in a drop-down list:
<form> <select id="mySelect" size="8"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> </form> <br> <p>Select an option in the dropdown list. Then click the button below to add a "Kiwi" option before the selected option.</p> <button type="button" onclick="myFunction()">Insert option before selected</button> <script> function myFunction() { var x = document.getElementById("mySelect"); if (x.selectedIndex >= 0) { var option = document.createElement("option"); option.text = "Kiwi"; var sel = x.options[x.selectedIndex]; x.add(option, sel); } } </script>
The remove()
method is used to remove an option from a drop-down list.
selectObject.remove(index)
<form> Select a fruit: <br> <select id="mySelect" size="4"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> </form> <button onclick="myFunction()">Remove selected fruit</button> <script> function myFunction() { var x = document.getElementById("mySelect"); x.remove(x.selectedIndex); } </script>
Remove the option with index "2" from a drop-down list:
var x = document.getElementById("mySelect"); x.remove(2);
Remove the last option from a drop-down list:
var x = document.getElementById("mySelect"); if (x.length > 0) { x.remove(x.length-1); }
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> <script> function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == "") { alert("Name must be filled out"); return false; } } </script>
<p>Please input a number between 1 and 10:</p> <input id="numb"> <button type="button" onclick="myFunction()">Submit</button> <p id="demo"></p> <script> function myFunction() { var x, text; // Get the value of the input field with id="numb" x = document.getElementById("numb").value; // If x is Not a Number or less than one or greater than 10 if (isNaN(x) || x < 1 || x > 10) { text = "Input not valid"; } else { text = "Input OK"; } document.getElementById("demo").innerHTML = text; } </script>
HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
HTML5 has introduced validation mechanisms for forms. In addition to semantic types for the <input> element (type=email, number, …), we also have constraint validation (required, maxlength, …) to ease the work of checking the form content on the client side.
Constraint validation is an algorithm browsers run natively when a form is submitted to determine its validity. On this approach, we took advantage of the constraint validation API to perform validations.
If an error occurs, checkValidity()
returns false. Then we use a property called validity from validation API to get the error of each input field.
The validity property gets a validityState object with the information of which validations failed and which didn’t. Here’s how it looks:
ValidityState = { badInput: false, customError: false, patternMismatch: false, rangeOverflow: false, rangeUnderflow: false, stepMismatch: false, tooLong: false, tooShort: false, typeMismatch: false, valid: false, valueMissing: true };
Finally, we map these properties with the data attributes of the input field to obtain the error messages.
The willValidate property indicates whether the node is a candidate for constraint validation. For submittable elements this will be set to true unless for some reason the node is barred from constraint validation, such as possessing the disabled attribute.
<div id="one"></div> <input type="text" id="two" /> <input type="text" id="three" disabled /> <script> document.getElementById('one').willValidate; //undefined document.getElementById('two').willValidate; //true document.getElementById('three').willValidate; //false </script>
The validity property of a DOM node returns a ValidityState object containing a number of boolean properties related to the validity of the data in the node.
customError: true if a custom validity message has been set per a call to setCustomValidity()
.
<input id="foo" /> <input id="bar" /> <script> document.getElementById('foo').validity.customError; //false document.getElementById('bar').setCustomValidity('Invalid'); document.getElementById('bar').validity.customError; //true </script>
patternMismatch: true if the node's value does not match its pattern attribute.
<input id="foo" pattern="[0-9]{4}" value="1234" /> <input id="bar" pattern="[0-9]{4}" value="ABCD" /> <script> document.getElementById('foo').validity.patternMismatch; //false document.getElementById('bar').validity.patternMismatch; //true </script>
rangeOverflow: true if the node's value is greater than its max attribute.
<input id="foo" type="number" max="2" value="1" /> <input id="bar" type="number" max="2" value="3" /> <script> document.getElementById('foo').validity.rangeOverflow; //false document.getElementById('bar').validity.rangeOverflow; //true </script>
rangeUnderflow: true if the node's value is less than its min attribute.
<input id="foo" type="number" min="2" value="3" /> <input id="bar" type="number" min="2" value="1" /> <script> document.getElementById('foo').validity.rangeUnderflow; //false document.getElementById('bar').validity.rangeUnderflow; //true </script>
stepMismatch: true if the node's value is invalid per its step attribute.
<input id="foo" type="number" step="2" value="4" /> <input id="bar" type="number" step="2" value="3" /> <script> document.getElementById('foo').validity.stepMismatch; //false document.getElementById('bar').validity.stepMismatch; //true </script>
tooLong: true if the node's value exceeds its maxlength attribute. All browsers prevent this from realistically occurring by preventing users from inputting values that exceed the maxlength.
typeMismatch:
true if an input node's value is invalid per its type attribute.<input id="foo" type="url" value="http://foo.com" /> <input id="bar" type="url" value="foo" /> <input id="foo2" type="email" value="foo@foo.com" /> <input id="bar2" type="email" value="bar" /> <script> document.getElementById('foo').validity.typeMismatch; //false document.getElementById('bar').validity.typeMismatch; //true document.getElementById('foo2').validity.typeMismatch; //false document.getElementById('bar2').validity.typeMismatch; //true </script>
valueMissing: true if the node has a required attribute but has no value.
<input id="foo" type="text" required value="foo" /> <input id="bar" type="text" required value="" /> <script> document.getElementById('foo').validity.valueMissing; //false document.getElementById('bar').validity.valueMissing; //true </script>
valid: true if all of the validity conditions listed above are false.
<input id="valid-1" type="text" required value="foo" /> <input id="valid-2" type="text" required value="" /> <script> document.getElementById('valid-1').validity.valid; //true document.getElementById('valid-2').validity.valid; //false </script>
The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails.
The browser provides a default localized message for this property. If the DOM node is not a candidate for constraint validation or if the node contains valid data validationMessage will be set to an empty string.
<input type="text" id="foo" required /> <script> document.getElementById('foo').validationMessage; //Chrome --> 'Please fill out this field.' //Firefox --> 'Please fill out this field.' //Safari --> 'value missing' //IE10 --> 'This is a required field.' //Opera --> '' </script>
The checkValidity
method on a form element node (e.g. input, select, textarea) returns true if the element contains valid data.
On form nodes it returns true if all of the form's children contain valid data.
<form id="form-1"> <input id="input-1" type="text" required /> </form> <form id="form-2"> <input id="input-2" type="text" /> </form> <script> document.getElementById('form-1').checkValidity(); //false document.getElementById('input-1').checkValidity(); //false document.getElementById('form-2').checkValidity(); //true document.getElementById('input-2').checkValidity(); //true </script>
Additionally, every time a form element's validity is checked via checkValidity
and fails, an invalid event is fired for that node. Using the example code above if you wanted to run something whenever the node with id input-1
was checked and contained invalid data you could use the following:
document.getElementById('input-1').addEventListener('invalid', function() { //... }, false);
There is no valid event, however, you can use the change event for notifications of when a field's validity changes.
document.getElementById('input-1').addEventListener('change', function(event) { if (event.target.validity.valid) { //Field contains valid data. } else { //Field contains invalid data. } }, false);
The setCustomValidity
method changes the validationMessage property as well as allows you to add custom validation rules.
Because it is setting the validationMessage passing in an empty string marks the field as valid and passing any other string marks the field as invalid. Unfortunately there is no way of setting the validationMessage without also changing the validity of a field.
For example, if we had two password fields we wanted to enforce be equal we could use the following:
if (document.getElementById('password1').value != document.getElementById('password2').value) { document.getElementById('password1').setCustomValidity('Passwords must match.'); } else { document.getElementById('password1').setCustomValidity(''); }
The boolean novalidate
attribute can be applied to form nodes. When present this attribute indicates that the form's data should not be validated when it is submitted.
<form novalidate> <input type="text" required /> <input type="submit" value="Submit" /> </form>
Because the above form has the novalidate
attribute it will submit even though it contains an empty required input.
The boolean formnovalidate
attribute can be applied to button and input nodes to prevent form validation. For example:
<form> <input type="text" required /> <input type="submit" value="Validate" /> <input type="submit" value="Do NOT Validate" formnovalidate /> </form>
In supporting browsers the :valid pseudo-classes will match form elements that meet their specified constraints and the :invalid pseudo-classes will match those that do not.
<form> <input type="text" id="foo" required /> <input type="text" id="bar" /> </form> <script> document.querySelectorAll('input[type="text"]:invalid'); //Matches input#foo document.querySelectorAll('input[type="text"]:valid'); //Matches input#bar </script>
By default Firefox places a red box-shadow and IE10 places a red outline on :invalid fields.
:invalid { box-shadow: none; /* FF */ outline: 0; /* IE 10 */ }
function myFunction() { var inpObj = document.getElementById("id1"); if (!inpObj.checkValidity()) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } else { document.getElementById("demo").innerHTML = "Input OK"; } }
function myFunction() { var inpObj = document.getElementById("id1"); //alert(inpObj.checkValidity()); // true or false if (inpObj.checkValidity()=== false ) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } if (inpObj.checkValidity()=== true ) { document.getElementById("demo").innerHTML = "Input OK"; } }
Content for the first footer section.
Content for the second footer section.
Content for the third footer section.