Array is a collection of similar data elements, means we can use array to store similar elements referenced under a common name.
In web development sometimes we need to group HTML form elements as arrays do. For example, you have a form where user has to select his hobbies from a group of check boxes as given below.
Sample Code
<form action="showlist.php" method="post" name="hobby_frm"> <h3> Select your hobbies </h3> <input type="checkbox" name="hobbies[]" value="hb1" /> Reading <br /> <input type="checkbox" name="hobbies[]" value="hb2" /> Surfing <br /> <input type="checkbox" name="hobbies[]" value="hb3" /> Listening to music <br /> <input type="submit" value="submit" /> </form>Please notice the name of all checkboxes hobbies[]
The above code will define an array with the name hobbies
Accessing form elements array using JavaScript
Now, let's see how to access the hobbies[] using JavaScript.
<script type="text/javascript"> var hobbies = document.hobby_frm.elements['hobbies[]']; var str = "Length : "+hobbies.length+"\n"; for( var i = 0; i < hobbies.length; i++ ) { str = str + "Hobby "+(i+1)+" : "+hobbies[i].value+"\n"; } alert(str); </script>Handle form elements array in PHP
In PHP, data sent from a form with post method is available in $_POST array.
We can access hobbies[] using the following code.
<?php
$hobbies = $_POST['hobbies']; // use name of the array as key
foreach( $hobbies as $value )
print $value;
?>
courtesey webdevelopment hosting company cochin kerala
yea awesome!. this kinda stuf is using when if multiple delete or select of elements are requiered..
ReplyDeletefor example the delete the selected mails in the inbox. or upload a series of file.