n w    w w w w

baner

Knowledge is power, and what about sharing the power. CodeGlobe is an open space where we programmers and techies share what we got special with us, The experience we got over years through our profession, the magical touch we made in solving logical hurdles, the new solutions we developed ourselves where others hesitated, alike all these, each and every bit of knowledge we got, let's just share with our pals. All we have to posses is just a mind to speak out and listen others. Registrations are open and hope you won't fail in grabbing this opportunity to become a Codeglober.


 


 

You are here:   Home / Web Development / PHP / Creating array of HTML form elements
large small default
Creating array of HTML form elements Print E-mail
Written by Musthafa   
Thursday, 14 July 2011 09:23

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;
?>

 

Comments (0)
Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:D:angry::angry-red::evil::idea::love::x:no-comments::ooo::pirate::?::(
:sleep::););)):0
Security
Please input the anti-spam code that you can read in the image.
Last Updated on Thursday, 14 July 2011 09:42