Working with Forms using the DOM
DOM Methods / Properties for Forms
| Method / Property | Description & Considerations | Applied To | Code Example |
|---|---|---|---|
| add() |
Used to add an <option> to a <select> menu.
The Passed two parameters. The first parameter is the new option node to insert, the second parameter is a reference to the existing option node that the new node will be inserted before. If the new option should be inserted at the end of the list, pass |
<select> |
selectElementRef.add(newOptionNode, existingOptionNodeRef)
|
| form |
This property is a reference to the <form> tag holding that form element.
|
Any form element |
formElementRef.form
|
| options[] |
Numerically indexed node list of all the <option> tags in a <select> menu; first one is 0.
|
<select> |
selectElementRef.options[2]
|
| selectedIndex |
Numerical position of the selected <option>.
|
<select> |
selectElementRef.selectedIndex
|
| remove() |
Deletes an <option> in a <select> menu, based on the index value passed (which represents the position of that option node in the options[] node list).
|
<select> |
selectElementRef.remove(3)
|
Additional DOM Considerations with Form Elements
Boolean Values
- Whenever you encounter an HTML attribute / property that does not have a value (such as
checked,selected,disabled, etc.) those are handled as Boolean values (trueorfalse). - Dot notation works best, such as
elementRef.disabled = false;
Node List of All Elements
- There is a DOM0
elements[]node list that you will sometimes see used. - This is a property of the
<form></form>element node. - It contains references to all the form elements within that form.
- Individual elements can be accessed by number (e.g.,
formElementRef.elements[5]), which is based on source code order, or by a string that matches to either theirnameorid(e.g.,formElementRef.elements['email']). - In the standardized DOM you would need to use
document.querySelectorAll("input, select, textarea, button").
Working with Select Menus
- To determine the value of whatever
<option></option>is chosen in a select menu you can access this atselectElementRef.value - To remove options from the
options[]node list, just set that option tonull, such asselectElementRef.options[4] = null;which removes the fifth option. All options after the fifth then move up one in the node list, to fill in the gap. - To clear all options just set the
lengthof the node list to0, such asselectElementRef.options.length = 0; - When dealing with a multiple-select menu you will need to use a loop to extract the selected options, since
selectElementRef.valueonly identifies the first option selected. You need to loop through theoptions[]node list and identify which ones wereselected, such asselectElementRef.options[i].selected === true
Practices to Avoid
- Avoid generating and inserting
<form></form>tags, as some browsers then redraw the entire screen and reset any values that were previously set. - It is best to have the
<form></form>already hard-coded and just append nodes inside of it. - Do not alter the
typeornameof a form element via JavaScript; significant cross-browser issues are likely to arise.
Select Menus for Navigation
- Sometimes JavaScript is used for Quick Link Menu functionality. This allows users to quickly navigate to other pages that are commonly sought out.
- To ensure accessibility for users favoring a keyboard, make sure that there is a button used to trigger the page change. Users can tab to the button when they have made the desired selection in the menu.
- The accessibility issue for keyboard users arises when there is no button in use and JavaScript is listening for 'change' or 'input' events from the select element and immediately loading the selected page. In those cases, there are some older browsers that fire the event with each arrow keypress inside the select menu, and in practice that means the user cannot get past the second option in the menu. They get to the menu via tabbing, are on the first option, then they press the down arrow key and the second option's page loads. On that new web page the menu has reset to the first option again.
- Since this example involves loading other URLs, CodePen's architecture is not ideal. For that reason the example is hosted on this site.
Structure (index.html)
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <title>Select Menus for Navigation</title> <meta charset="utf-8" /> <link rel="stylesheet" href="select_navigation.css" /> </head> <body> <p>Home Page</p> <form method="post" action="#"></form> <script src="select_navigation.js"></script> </body> </html>
Presentation (select_navigation.css)
body, select, option {font: 75%/2.0 verdana, sans-serif;}
select, option {font-size: 100%;}
select {margin-right: .5em;}
Behavior (select_navigation.js)
"use strict";
const menu = {
// select menu node
theSelectMenu : document.createElement('select'),
// button node
theGoButton : document.createElement('input'),
// reference to form element
container : document.getElementsByTagName('form')[0],
// visible text for menu options
labels : ['Please choose...','Home','Latest News','Who We Are','Our Products','Our Services','Contact'],
// values for menu options
urls : ['','index','latest_news','who_we_are','our_products','our_services','contact'],
// number of items in menu
allMenuItems : 0,
init : function() {
this.allMenuItems = this.urls.length;
// build the menu and insert it into the document
this.buildMenu();
},
buildMenu : function() {
// populate the menu
for (let i=0; i<this.allMenuItems; i++) {
const optionToAdd = document.createElement('option');
optionToAdd.value = this.urls[i] + '.html';
// if there is no URL, reassign value to be empty
if (this.urls[i] === '') { optionToAdd.value = ''; }
// append text inside option and append option to menu
optionToAdd.appendChild(document.createTextNode(this.labels[i]));
this.theSelectMenu.appendChild(optionToAdd);
}
// configure the 'Go' button
this.theGoButton.type = 'button';
this.theGoButton.value = 'Go!';
// assign click event
this.theGoButton.addEventListener('click', this.changePage, false);
// append select menu and button at end of document
this.container.appendChild(this.theSelectMenu);
this.container.appendChild(this.theGoButton);
},
changePage : function() {
// ignore the 'Please choose...', which has an empty (false) value
if (menu.theSelectMenu.value !== '') {
// the location object is part of the Browser Object Model (BOM)
location.href = menu.theSelectMenu.value;
}
}
}
menu.init();
Dynamic Select Menus
- This functionality involves selections in one
<select>menu causing another menu to be populated. - This approach uses the 'change' event for one menu to trigger changes in the other menu.
- Since we are not loading a different page when 'change' fires, this approach is acceptable from an accessibility perspective.
See the Pen Dynamic Select Menus by Jason Withrow (@jwithrow) on CodePen.