Form Properties and Methods in JavaScript
Forms are an essential part of web applications, and JavaScript provides multiple ways to interact with them using properties and methods.
🔹 1. Accessing Forms and Elements
Forms are accessed via the document.forms
collection, and form elements are accessed through their names or indexes.
✔ Example: Access a Form by Name
✔ Example: Access a Form by Index
✔ Example: Access Form Elements
✅ HTML Example
🔹 2. Form Properties
Property | Description |
---|---|
form.elements | Returns a collection of all elements inside the form. |
form.action | Gets or sets the form submission URL. |
form.method | Gets or sets the HTTP method (GET , POST ). |
form.name | Gets or sets the form name. |
form.length | Returns the number of form elements. |
✔ Example: Accessing Form Properties
✔ Example: Change Form Action and Method
🔹 3. Input Properties and Methods
Each form input field has properties that allow reading and modifying values.
Property | Description |
---|---|
input.value | Gets or sets the input value. |
input.type | Gets or sets the input type (text , password , checkbox , etc.). |
input.name | Gets or sets the input name attribute. |
input.disabled | Enables or disables the input. |
input.checked | Checks or unchecks a checkbox or radio button. |
✔ Example: Get and Set Input Values
✔ Example: Enable/Disable Input Field
✔ Example: Check a Checkbox
✅ HTML Example with Checkbox
🔹 4. Handling Form Submission
Forms are submitted using the .submit()
method or the default form submission behavior.
✔ Example: Prevent Default Form Submission
✔ Example: Submit a Form Using JavaScript
🔹 5. Validating Form Data
✔ Example: Validate Before Submitting
🎯 Conclusion
✅ Accessing Forms → document.forms["formName"]
✅ Getting Input Values → input.value
✅ Changing Form Action & Method → form.action = "newURL"
✅ Handling Form Submission → form.submit()
, event.preventDefault()
✅ Validating Data → if (input.value === "") { alert("Error") }
🚀 Now you can control forms like a pro!