Skip to main content

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

HTML
<form id="myForm">
<!-- form elements go here -->
</form>
JavaScript
const form = document.getElementById('myForm');
console.log(form);
Live Playground, Try it Yourself

Accessing a Form by Index

HTML
<form>
<input type="text" name="username" />
<input type="password" name="password" />
</form>
JavaScript
const form = document.forms[0];
console.log(form);
Live Playground, Try it Yourself

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

HTML
<form id="myForm">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
JavaScript
const form = document.getElementById('myForm');
const usernameInput = form.elements[0];
const passwordInput = form.elements[1];

console.log(usernameInput, passwordInput);
Live Playground, Try it Yourself

Accessing Form Elements by Name

HTML
<form id="myForm">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
JavaScript
const form = document.getElementById('myForm');
const usernameInput = form.elements['username'];
const passwordInput = form.elements['password'];

console.log(usernameInput, passwordInput);
Live Playground, Try it Yourself

Getting and Setting Form Element Values

To get or set the value of a form element, you can use the value property.

HTML
<form id="myForm">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
JavaScript
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';
Live Playground, Try it Yourself

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.