Accessing Forms in JavaScript DOM (Live Playground)
In this tutorial, we will explore how to access and interact with HTML forms using JavaScript DOM. This knowledge is essential for creating dynamic and user-friendly web applications that process user input.
Accessing a Form
To access a form in JavaScript, you can use the getElementById()
method, providing the form's id
attribute as an argument. Alternatively, you can use the document.forms
collection, which contains all the forms within the document.
Accessing a Form by ID
<form id="myForm">
<!-- form elements go here -->
</form>
const form = document.getElementById('myForm');
console.log(form);
Accessing a Form by Index
<form>
<input type="text" name="username" />
<input type="password" name="password" />
</form>
const form = document.forms[0];
console.log(form);
Accessing Form Elements
Once you have a reference to a form, you can access its elements using the elements
property. The elements
property returns an HTMLFormControlsCollection, which behaves like an array and contains all the form elements.
Accessing Form Elements by Index
<form id="myForm">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
const form = document.getElementById('myForm');
const usernameInput = form.elements[0];
const passwordInput = form.elements[1];
console.log(usernameInput, passwordInput);
Accessing Form Elements by Name
<form id="myForm">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
const form = document.getElementById('myForm');
const usernameInput = form.elements['username'];
const passwordInput = form.elements['password'];
console.log(usernameInput, passwordInput);
Getting and Setting Form Element Values
To get or set the value of a form element, you can use the value
property.
<form id="myForm">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
const form = document.getElementById('myForm');
const usernameInput = form.elements['username'];
const passwordInput = form.elements['password'];
// Getting the values of form elements
console.log('Username:', usernameInput.value);
console.log('Password:', passwordInput.value);
// Setting the values of form elements
usernameInput.value = 'JohnDoe';
passwordInput.value = 'secret';
Conclusion
In this tutorial, we have learned how to access and interact with HTML forms using JavaScript DOM. With this knowledge, you can create dynamic and user-friendly web applications that process user input, enhancing the overall user experience.