Click to See Complete Forum and Search --> : php and forms


paperbox005
09-29-2004, 08:53 PM
how can i create a page where i have a textbox which i can enter some data, and when i click the submit button it gives me another textbox on the same page, everytime i click the submit button a new textbox appears, so if i press it 3 times i have 3 textboxes. how is this done in php?

yuna
09-29-2004, 10:32 PM
How about something like this?


<form method="post" action="<?php echo $_SERVER["PHP_SELF"] ?>">

<?php
# if this is the first time we've viewed this page,
# set the counter to zero
if (!isset($_POST["nboxes"])) { $nboxes=1; }

# extract the $textbox array from the POST
$textbox=$_POST["textbox"];

# display boxes with values stored as ordered array $textbox[]
for ($i=0; $i<$nboxes; $i++) { ?>

<textarea name="textbox[<?php echo $i ?>]" rows="5"
cols="50"><?php echo trim($textbox[$i]) ?></textarea>
<input type="submit" value="Gimme another box!">

<?php
}

# add one to $nboxes so we'll display another box when submitted
?>
<input type="hidden" name="nboxes" value="<?php echo $nboxes+1 ?>">
</form>



When the page is first displayed via a GET, $_POST["nboxes"] is empty, so $nboxes is set to one, and one box is displayed. Then $nboxes is incremented and passed back to the script via POST. The data entered into the text boxes are stored in the array $textbox[0], $textbox[1], etc., and displayed each time the page is submitted.

Note that you need to have the <?php ?> tags immediately adjacent to the <textarea></textarea> tags to avoid embedding spaces before and after the contents of the box. I also use the trim() function to eliminate any extraneous leading or trailing whitespace.