Sunday, 27 November 2011

Varying number of text boxes in HTML form by user

Here I am introducing Variable number of text boxes in HTML form.That is a HTML form in which user can add any number of text boxes as options using PHP.Users can also remove added text box if required.


        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <table  width="100%" height="100%" align="center">
            <tr><td colspan="4">
        <form name="q_form" action="question_submit.php" method="post">
<tr height="100">    <td>   Question</td><td colspan="3"><textarea input  rows="4" cols="79" name="question"></textarea></td></tr>
<?php $n=$_GET["num"];

   echo "<tr height=\"50\" ><td>Option $i</td><td><input type=\"text\" name=\"$i\" size=\"58\"></td>";

echo "<tr><td>";
  echo" <a href=\"question.php?num=$na\">Add</a>";
echo "<a href=\"question.php?num=$nr\">Remove</a>";
  echo "</tr></td>";

    <tr align="center"><td colspan="4" align="center" height="75">    <input type="submit" value="Submit" ></td></tr>


The resulting HTML page will be look like above.

Here I am using URL to pass the number of text boxes required like this
  echo" <a href=\"question.php?num=$na\">Add</a>";
echo "<a href=\"question.php?num=$nr\">Remove</a>";

the value passed by $na or $nr is in num parameter of URL.It will be like this
This 'num' parameter is parsed into $n variable using php like this ,
That is the value we send directly to the URL is treated as form submitted using get method.

Then using a loop display '$n' number of text boxes in the page.
Then execute this code 

here $na increased by one than $n
but $nr decreased by one than $n.

Then gives to links Add,Remove
echo" <a href=\"question.php?num=$na\">Add</a>";
echo "<a href=\"question.php?num=$nr\">Remove</a>";

That is if user click 'Add' link the 'num' parameter in the URL will be increased by one than the current page.
If  user click 'Remove' link the 'num' parameter in the URL will be decreased by one than the current page.

Thus it will give a flexible page,in which user can add/remove any number of option fields.

One important thing to note that in the first time page is loaded there will be no option text boxes because
the 'num' parameter in URL will be zero.
We can tolerate by call this page URL from another link and put 'num'
as 2.

That is in a new html page type like this
<a href="answer.php?num=2">Click to next Page </a>

Where answer.php is the name of html page we created earlier.

You can also see another example like this :-  Change font size of text in HTML page dynamically using php

Hope that this post will be helpful to you.  Thanks... 

No comments:

Post a Comment

Search This Blog