Accessing Form Elements Array with JavaScript

This article shows how you can access an array of HTML form elements using JavaScript.

Suppose you have an HTML form like this:

<form name="myform" method="post" action="form-processor.php">
    Name: <input type="text" name="myname"> <br/>
    Favorite fruits: <br/>
    <input type="checkbox" name="fav[]">Apple <br/>
    <input type="checkbox" name="fav[]">Banana <br/>
    <input type="checkbox" name="fav[]">Orange <br/>
    <input type="checkbox" name="fav[]">Mango <br/>

Sometimes you need to use JavaScript to access the elements’ properties, e.g to check which checkboxes are selected, which text fields contain values, etc. Normally we can use the element’s name directly and read its properties as follows:

<script type="text/javascript">
if (document.myform.myname.value == '') {
    window.alert('Please fill in your name');

However, it will not work for ‘fav[]‘ elements. You need to use ‘elements’ property to access them:

<script type="text/javascript">
// How many options we have?
var fav_count = document.getElementByName('fav[]');
var is_checked = false;

for (var i = 0; i < fav_count; i++) {
    if (document.myform.elements['fav[]'].checked) {
        is_checked = true;

if (is_checked == false) {
    window.alert('Please select at least 1 favorite fruit');