Mastering JavaScript Forms, DOM, and BOM APIs
JavaScript Form Object
The Form Object in JavaScript represents an HTML form. It is used to access and control form elements such as text fields, buttons, checkboxes, and radio buttons. Using the form object, developers can handle form data and perform validation easily. Forms are accessed through the document.forms collection.
Syntax
document.forms["formname"]
Example: document.forms["myform"] (Accesses the form named ‘myform’)
Properties
- action: Specifies the URL where form data is sent.
- method: Specifies the HTTP method (GET or POST) used for sending data.
- elements: Returns all form elements.
- length: Returns the number of elements in a form.
Methods
- submit(): Used to submit the form data.
- reset(): Used to reset form values.
Accessing Data from Forms
Accessing data from forms involves retrieving values entered by users. This is essential for validation and processing.
Methods to Access Data
- By Form Name:
document.formname.elementname.value - By getElementById():
document.getElementById("id").value - Radio Buttons:
document.myform.gender.value - Checkboxes:
document.getElementById("check").checked
Additional Form Attributes
HTML provides attributes to improve user interaction and data integrity:
- placeholder: Displays hint text inside an input field.
- required: Makes a field mandatory.
- readonly: Allows users to view data but not modify it.
- disabled: Disables the input field.
- autofocus: Automatically focuses the field on page load.
- maxlength: Limits the number of characters.
Validation APIs
HTML5 provides built-in validation APIs to check user input without complex JavaScript.
Key Properties
- validity: Checks if input data is valid.
- validationMessage: Displays the error message.
- willValidate: Checks if an element can be validated.
Key Methods
- checkValidity(): Returns true if form data is valid.
- setCustomValidity(): Sets a custom error message.
DOM vs. BOM
The Document Object Model (DOM) represents the structure of an HTML document, while the Browser Object Model (BOM) allows interaction with the browser window.
| Feature | DOM | BOM |
|---|---|---|
| Representation | document object | window object |
| Scope | Webpage content | Browser window |
| Standard | W3C Standard | No official standard |
BOM Navigator Object
The Navigator Object provides information about the user’s browser.
Common Properties
- appName: Returns the browser name.
- appVersion: Returns browser version information.
- language: Returns the browser language.
- cookieEnabled: Checks if cookies are enabled.
- onLine: Checks if the browser is online.
- platform: Returns the operating system platform.
