Tue, 09 February 2010
Home
Articles
Books
Search
Tools
Whois
Links
Sitemap
Contact us
Privacy policy
Free Magazines
Home arrow Articles arrow JavaScript arrow Accessing Form Elements Array with JavaScript

Accessing Form Elements Array with JavaScript PDF Print E-mail

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"> 

    Favorite fruits: 

    <input type="checkbox" name="fav[]">Apple 

    <input type="checkbox" name="fav[]">Banana 

    <input type="checkbox" name="fav[]">Orange 

    <input type="checkbox" name="fav[]">Mango 

</form>

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>
if (document.myform.myname.value == '') {
    window.alert('Please fill in your name');
}
</script>

female urinary

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

<script>
// 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;
        break;
    }
}

if (is_checked == false) {
    window.alert('Please select at least 1 favorite fruit');
}
</script>

 

Powered by
Syndicate