In JavaScript, a form is represented by an HtmlFormElement object. And after creating the form, we can refer to it in various ways.
The first way is to directly refer to the form name:
<form name="search"> </form>
var searchForm = document.search;
The second way is to access the collection of forms of the document and search for the desired form in it:
<head> <title>Test</title> </head> <body> <form name="search"></form> <form name="settings"></form> <script> var searchForm; for (var i = 0; i < document.forms.length; i++) { if(document.forms[i].name==="search") searchForm = document.forms[i]; } document.write(searchForm.name); </script> </body>
A simplified version:
var searchForm = document.forms["search"];
You can use standard methods to search for a form element, for example, by id, by tag, or by selector:
var searchForm = document.getElementsByTagname("form")[0]
The form has a number of properties, of which the most important are the name property discussed above, as well as the elements property, which contains a collection of form elements:
<form name="search"> <input type="text" name="key" > <input type="submit" name="send" > </form>
var searchForm = document.forms["search"]; for(var i=0; i < searchForm.elements.length; i++) document.write(searchForm.elements[i].name);//key, send
Among the form methods, we should note the submit() method, which sends the form data to the server, and the reset() method, which clears the form fields:
var searchForm = document.forms["search"]; searchForm.submit();//send form data searchForm.reset();//clear the form
Form elements
A form can contain various HTML input elements: input, textarea, button, select, etc. But they all have a number of common properties and methods.
Just like a form, form elements have a name property that can be used to get the value of the name attribute:
<form name="search"> <input type="text" name="key" value="hello world"> <input type="submit" name="send"> </form>
var searchForm = document.forms["search"]; //print the name of all elements for(var i=0; i < searchForm.elements.length;i++) document.write(searchForm.elements[i].name); // get the text field by name var keyBox = searchForm.elements["key"]; document.write(keyBox.name); // key
Another important property is the value property, which allows you to get or change the value of a field:
var searchForm = document.forms["search"]; var keyBox = searchForm.elements["key"]; document.write(keyBox.value); // hello world // set value keyBox.value = "Hello World";
Using the form property, you can get the parent object of the form:
var searchForm = document.forms["search"]; var keyBox = searchForm.elements["key"]; document.write(keyBox.form.name); // search
The type property allows you to get the type of the input field. This is either the name of an element tag (such as textarea) or the value of the type attribute on input elements.
From the methods, we can distinguish the methods focus() (sets focus on the element) and blur() (removes focus from the element):
var searchForm = document.forms["search"]; var keyBox = searchForm.elements["key"]; keyBox.focus();
Form buttons
To create a button, use the button element or the input element:
<button name="send">Send form</button> <input type="submit" name="send" value="Send form" />
When you click on any of these two button options, the form is sent to the address specified in the form’s action attribute, or to the web page address if the action attribute is not specified.
<head> <title>Test</title> </head> <body> <form name="search"> <input type="text" name="key"></input> <input type="submit" name="send" value="Send" /> </form> <script> function sendForm(e){ // get the value of the key field var keyBox = document.search.key; var val = keyBox.value; if (val.length > 5){ alert("error, must be 5 symbols"); e.preventDefault(); } else alert("Sended"); } var sendButton = document.search.send; sendButton.addEventListener("click", sendForm); </script> </body>
We can also, if necessary, change the address to which the data is sent when sending:
function sendForm(e){ // get the value of the key field var keyBox = document.search.key; var val = keyBox.value; if(val.length > 5){ alert("Invalid string length"); document.search.action="PostForm"; } else alert("Sending allowed"); }
Clearing the form
The following buttons, which are equivalent in functionality, are intended for clearing the form:
<button type="reset">Clear</button> <input type="reset" value="Clear" />
We can also clear form fields using the reset() method:
function sendForm(e){ //get the value of the key field var keyBox = document.search.key; var val = keyBox.value; if(val.length > 5){ alert("Invalid string length"); document.search.reset(); e.preventDefault(); } else alert("Sending allowed"); }
In addition to special submit and clear buttons, a regular button can also be used on the form:
<input type="button" name="send" value="Send" />
When you click on a button like this, no data is sent, although a click event is also generated:
<head> <title>Test Form</title> </head> <body> <form name="search"> <input type="text" name="key" placeholder="Enter the key"> <input type="button" name="print" value="Peint" /> </form> <div id="printBlock"></div> <script> function printForm(e) { // get the value of the key field var keyBox = document.search.key; var val = keyBox.value; // get printBlock element var printBlock = document.getElementById("printBlock"); // create a new paragraph var pElement = document.createElement("p"); // set its text pElement.textContent = val; // add paragraph to printBlock printBlock.appendChild(pElement); } var printButton = document.search.print; printButton.addEventListener("click", printForm); </script> </body>
When the button is clicked, we get the text entered in the text field, create a new paragraph element for this text, and add a paragraph to the printBlock element.
Type text
Elements are intended for entering textual information:
<input type="text" name="nickname" size="50" maxlength="55" value="New Player" />
This element supports a number of events, in particular:
- focus – happens when focus is received
- blur – occurs when focus is lost
- change – occurs when the field value changes
- select – occurs when text is selected in a text field
- keydown – occurs when a keyboard key is pressed
- keypress – occurs when a keyboard key is pressed for printable characters
- keyup – occurs when a previously pressed keyboard key is released
Let’s look at an example:
<head> <title>Test</title> </head> <body> <form name="search"> <input type="text" name="key" placeholder="Pls enter yours nickname"> <input type="button" name="print" value="Print" /> </form> <div id="printBlock"></div> <script> var keyBox = document.search.key; // text change handler function onchange(e) { // get the printBlock element var printBlock = document.getElementById("printBlock"); // get new value var val = e.target.value; // set value printBlock.textContent = val; } // focus loss handling function onblur(e) { // get its value and trim all spaces var text = keyBox.value.trim(); if (text === "") keyBox.style.borderColor = "red"; else keyBox.style.borderColor = "green"; } //getting focus function onfocus(e) { keyBox.style.borderColor = "blue"; } //listening for text change event keyBox.addEventListener("change", onchange); // listen for the loss of focus event keyBox.addEventListener("blur", onblur); //listening for the focus event keyBox.addEventListener("focus", onfocus); </script> </body>
Type password
The type=”password” field is for entering a password.
In terms of functionality, it is in many ways similar to a regular text field, with the exception that for the characters you enter mask is used:
<input type="password" name="password" />
Textarea
The textarea element is used to create multiline text fields:
<textarea rows="10" cols="50" name="textArea"></textarea>
In functionality, it is in many ways similar to a regular text field.
Value hidden from users
If we need some value on the form, but that it is hidden from the user, then hidden fields can be used for this:
<input type="hidden" name="id" value="345">
Hidden fields are not usually handled by events, but just like other elements, we can get its value or change it in JavaScript.
This element generates all the same events as a regular text field.
Checkbox
Checkboxes represent a checkbox that can be checked and is created with an type=”checkbox”.
The distinguishing feature of a checkbox is the checked property, which is set to true when checked:
<form name="myForm"> <input type="checkbox" name="enabled" checked><span>Enable</span> </form> <div id="printBlock"></div>
In JS:
var enabledBox = document.myForm.enabled; function onclick(e){ var printBlock = document.getElementById("printBlock"); var enabled = e.target.checked; printBlock.textContent = enabled; } enabledBox.addEventListener("click", onclick);
Clicking the checkbox fires a click event. In this case, when processing this event, we simply display information, whether the given checkbox is checked, in the div block.
Radio
Radio buttons represent groups of buttons from which we can only select one. Radio buttons are created by the type=”radio” element:
<form name="myForm"> <input type="radio" name="languages" checked="checked" value="Java" /><span>Java</span> <input type="radio" name="languages" value="C#" /><span>C#</span> <input type="radio" name="languages" value="C++" /><span>C++</span> </form> <div id="printBlock"></div>
function onclick(e){ var printBlock = document.getElementById("printBlock"); var language = e.target.value; printBlock.textContent = language; } for (var i = 0; i < myForm.languages.length; i++) { myForm.languages[i].addEventListener("click", onclick); }
Each radio button, like the check box, has a checked property that returns true if the radio button is selected. For example, note the last switch:
myForm.languages[myForm.languages.length-1].checked = true;
Select
The HTML select element is used to create a list. Moreover, with its help, you can create both drop-down lists and regular with single or multiple choice.
<select name="language" size="4"> <option value="JS" selected="selected">JavaScript</option> <option value="Java">Java</option> <option value="C#">C#</option> <option value="C++">C++</option> </select>
size=”4″ – allows you to set how many items will be displayed at once in the list
size=”1″ – make the list drop
multiple – allows you to select multiple values
In JavaScript, a select element corresponds to an HTMLSelectElement object, and an option element corresponds to an HtmlOptionElement object, or just Option.
All list elements in javascript are available through the options collection. And each HtmlOptionElement object has properties:
- index – index in the options collection
- text – display text
- value – element value
For example, we will get the first element of the list and display all the information about it through its properties:
<form name="myForm"> <select name="language" size="4"> <option value="JS" selected="selected">JavaScript</option> <option value="Java">Java</option> <option value="CS">C#</option> <option value="CPP">C++</option> </select> </form>
in JS:
var firstLanguage = myForm.language.options[0]; document.write("Index: " + firstLanguage.index ); document.write("Text: " + firstLanguage.text); document.write("Value: " + firstLanguage.value);
We can not only get elements, but also dynamically manipulate the list. For example, let’s add and remove list objects:
<form name="myForm"> <select name="language" size="5"> <option value="JS" selected="selected">JavaScript</option> <option value="Java">Java</option> <option value="CS">C#</option> <option value="CPP">C++</option> </select> <input type="text" name="textInput" placeholder="Enter yours text" /> <input type="text" name="valueInput" placeholder="Enter value" /> <input type="button" name="addButton" value="Add button" /> <input type="button" name="removeButton" value="Remove button" /></p>
var addButton = myForm.addButton, removeButton = myForm.removeButton, languagesSelect = myForm.language; // handler for adding an element function addOption() { // get the text for the element var text = myForm.textInput.value; var value = myForm.valueInput.value; // create a new element var newOption = new Option(text, value); languagesSelect.options[languagesSelect.options.length] = newOption; } // element removal handler function removeOption() { var selectedIndex = languagesSelect.options.selectedIndex; //remove element languagesSelect.options[selectedIndex] = null; } addButton.addEventListener("click", addOption); removeButton.addEventListener("click", removeOption);
To add/remove, you can also alternatively use the methods of the select element:
languagesSelect.add(newOption); languagesSelect.remove(selectedIndex);
Select events
The select element supports three events:
- blur – loss of focus
- focus – getting focus
- change – changing the selected item in the list
<form name="myForm"> <select name="language" size="5"> <option value="JS" selected="selected">JavaScript</option> <option value="Java">Java</option> <option value="CS">C#</option> <option value="CPP">C++</option> </select> </form> <div id="selection"></div>
var languagesSelect = myForm.language; function changeOption() { var selection = document.getElementById("selection"); var selectedOption = languagesSelect.options[languagesSelect.selectedIndex]; selection.textContent = selectedOption.text; } languagesSelect.addEventListener("change", changeOption);