I have two file. One is index.php and the other is display.php.
Index.php contains a form and after submitting, it generates a json value and displays that in a textarea, so I might edit before I press the "generate" button and it redirects me to the display.php where a for loop generates a html template according to the posted son data. It works perfectly with up to 3 item, but if I use 4 or more, it drops me a fatal error with memory limit. As I still got errors after increasing the limit, I tried the following on the display.php:
ini_set('memory_limit', '-1');
set_time_limit(0);
After this, it drops me an error 503 - service unavailable.
I don't know what to do, I am asking your help.
index.php:
<meta charset="utf-8">
<style>
pre, textarea { background-color:#31495D;min-height:300px;color:white;margin-bottom:50px;padding:25px;width:100%;display:block;border-bottom:5px solid #A058B3; }
.submit { padding:15px;background-color:green;color:white;border:none;font-size:12px;width:150px;margin:0 auto;margin-top:15px;margin-bottom:15px }
</style>
<?php
$json = json_encode($_POST, JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE);
echo "
<h2>JSON for template</h2>
<form action='display.php' method='post'>
<textarea name='json'>$json</textarea>
<input class='submit' type='submit' value='Generate Template'>
</form>
";
$json = json_decode($json, true);
?>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="url[]" placeholder="http://www.example.com/"/><input type="text" name="name[]" placeholder="Name"/><input type="text" name="subtext[]" placeholder="Subtext"/><input type="text" name="image[]" placeholder="Image URL"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<label>Title of Block <input type="text" name="title"></label><br>
<label>Heading of Block <input type="text" name="heading"></label><br><br>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="url[]" placeholder="http://www.example.com/"/><input type="text" name="name[]" placeholder="Name"/><input type="text" name="subtext[]" placeholder="Subtext"/><input type="text" name="image[]" placeholder="Image URL"/></div>
</div>
<br><br>
<input type="submit" value="Generate Code">
</form>
And the display.php
<?php
$json = json_decode($_POST['json'], true);
$c = count($json);
$i = 0;
$rows = 3;
$content = "<table>";
for($i=0; $i < count($json["name"]); $i++) {
$content .=
'<td width="226" valign="top" style="padding:5px;padding-bottom:20px;" class="m-stack m-pad-b">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:22px;padding-bottom:5px; mso-line-height-rule:exactly; line-height: 18px; padding-top: 8px;">
<a href="'.$json['url'][$i].'" target="_blank" style="text-decoration:none;color:#0896ff; display:block;">
'.$json['name'][$i].'<br><span style="color: #7d90a6; font-size: 14px;">'.$json['subtext'][$i].'</span>
</a>
</td>
</tr>
<tr>
<td background="'.$json['image'][$i].'" width="226" height="226" valign="top" style="background-size:cover; background-position:center center; border-radius:6px 6px 0 0;" class="m-ufi-bg">
<!--[if gte mso 9]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:226px;height:226px;">
<v:fill type="frame" src="'.$json['image'][$i].'" color="#7bceeb" />
</v:rect>
<![endif]-->
</td>
</tr>
</table>
</td>
';
if($i == 3) { $content .= '</tr><tr>'; unset($i); $i == 0; }
}
echo "</table>";
echo $content;
This is just an experiment for me, any suggestion / critique is appreciated. Thanks in advance.
You are reseting $i to 0 so it never becomes greater than count($json) and your for loop becomes infinite
Related
I’m new to PHP and making a website to add an arbitrary number of values in a given base. How would I generate several fields based on a user’s input in a previous field?
The simple code without any validation will be like this:
<?php
if (isset($_POST['count_of_fields'])) {
echo '<form method="POST" action="">';
for ($i = 0; $i < (int) $_POST['count_of_fields']; ++$i) {
echo '<input type="text" name="field[$i]" /><br>';
}
echo ' <input type="submit"></form>';
} else {
echo '
<form method="POST" action="">
<input type="number" name="count_of_fields">
<input type="submit">
</form>
';
}
Beside the answer from #lis-dev which is generating fields in server side you will have to load the page each time to render the new fields, let's use JavaScript to do that for you without refreshing the page. and yes using mix and max you can put limit also
function generate()
{
var value = parseInt(document.getElementById("no").value);
for(var i =1; i <= value ; i++)
{
var input = document.createElement("input");
var br = document.createElement("br");
input.type = "text";
input.placeholder = "I am dynamic field " + i;
document.getElementById('form').appendChild(input);
document.getElementById('form').appendChild(br);
}
}
<html>
<head>
<title>dynamic fields test</title>
</head>
<body>
<form id="form">
<input id="no" type="text" min="5" max="10" placeholder="Enter no of Fields">
<input type="button" value="Generate" onclick="generate()">
<br />
</form>
</body>
</html>
I have a form that users use to save information to text files, then a drop-down list that pulls the names of their files and displays that information back into the text fields, however I am trying to figure out how I can clear the text fields when selecting one value. I have an < option value="0" >(Add New Code) aside from my php that is simply as a placeholder so they can use the form to save data. What I am trying to figure out is how to clear the text-boxes whenever they select that particular drop down. I would also like to add a delete button that appears whenever a file selection is made from the drop-down list. Below is my relevant coding.
thank you for the help on the display issue and css button am trying to figure out now the php script for the delete button to delete the currently selected file.
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select size="1" name="CodeList" id="CodeList" onchange="CodeChange();"><option value="0">(Add New Code)</option>
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo "<option>" . $file . "</option>";
}
}
?>
</select>
<h3>Saved Codes</h3>
<form method="post" action="/evo/avsaveprocess.php">
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<table width="100%" border="0">
<tr>
<td>Description:</td>
<td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
</tr>
<tr>
<td valign="top">Code:</td>
<td>
<textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
<script>
$(document).ready(function(){
// apply a change event
$('#CodeList').change(function() {
// update input box with the currently selected value
$('#CodeName').val($(this).val());
$.get( '<? echo $directory ?>' + '/' + $('#CodeName').val(), function( data ) {
$( "#CodeValue" ).text( data );
});
});
});
< option value="0" >(Add New Code)< /option >
I do not understand the purpose of value="0"
When an <option> is selected you retrieve the .selectedIndex from the <select id="id">
Then you use the selectedIndex to access the selected option with .options[selectedIndex].text
I do not do jQuery, but you can easily translate.
I am assuming you want to clear or change the option text.
This is the code to clear text in a Select Option:
add text to the empty string to change text value.
var ndx = document.getElementById('id').selectedIndex;
document.getElementById('id').options[ndx].text='';
jQuery (not mine)
(from get index of selected option with jQuery)
$("#id option:selected").index()
(from jQuery get specific option tag text)
$("#id[ndx]").text();
Delete Button HTML:
<button type="button" id="b1" class="hide">Delete</button>
Delete Button CSS:
.hide{display:none;}
Delete Button JS
document.getElementById('b1').style.display='block';
This worked:
<!DOCTYPE html>
<html lang="en"><head><title>Unhide Delete</title>
<style type="text/css">
.hide{display:none;}
</style></head><body>
<button type="button" id="b1" class="hide">Delete</button>
<script type="text/javascript">
//<![CDATA[
document.getElementById('b1').style.display='block';
//]]>
</script></body></html>
This one toggles the Delete Button
<!DOCTYPE html>
<html lang="en"><head><title>Unhide Delete</title>
<style type="text/css">
.hide{display:none;}
</style></head><body>
<button type="button" onclick="hideShow()">Show Hide Delete</button><br/> <br/>
<button type="button" id="b1" class="hide">Delete</button>
<script type="text/javascript">
//<![CDATA[
var toggle = new Array();
toggle['none'] = 'block';
toggle['block'] = 'none';
var del = document.getElementById('b1');
del.style.display='block';
function hideShow(){
del.style.display=toggle[del.style.display];
}
//]]>
</script></body></html>
My version of your page:
And I filtered the files to include only those with an extension of .php for my testing
if(pathinfo($file,PATHINFO_EXTENSION) == 'php' ){
Problems and solutions:
Contents of file could not be stored in variable.
Converted newlines to preg_replace('/\n/','',$contents);
converted < to < preg_replace('/</','<',$contents);
converted > to > preg_replace('/>/','>',$contents);');
Then when setting the text to the contents of the contents array the >,> and had to be converted back to their original characters.
var temp = contents[ndx].replace(/</g,'<');
temp = temp.replace(/>/g,'>');
txt.value= temp.replace(/<br>/g,"\\n");
textarea needed to be resized to show contents
added scrollbars
CSS:overflow:scroll;
set to height of content
txt.style.height= txt.scrollHeight;
When content very large textarea was too big.
Limited textarea height to fit in Browser window.
var maxHeight = (window.innerHeight - txt.offsetTop) - 40;
var h = txt.scrollHeight;
if(h > maxHeight){h = maxHeight;}
txt.style.height = h + 'px';
The + 'px' is important
When smaller file followed lage file the text area height had to be reduced
txt.style.height = '100px';
First option need to be blank other wise first option could not easily be selected because there would be no change event.
Made first array element blank
\ncontents[0] = '';\n
set $ndx = 1 rather than zero
file needed directory for file_get_contents without adding directory to options
Changed comma to dot
file_get_contents($directory , $file);
file_get_contents($directory . $file);
Now I am fairly satisfied with this page:
<?php ob_start("ob_gzhandler");
header('Content-Type: text/html; charset=utf-8');
header('Connection: Keep-Alive');
header('Keep-Alive: timeout=5, max=100');
header('Cache-Control: max-age=120');
echo <<<EOT
<!DOCTYPE html>
<html lang="en"><head><title>Code</title>
<style type="text/css">
#CodeValue{width:50%;background:#eff; width:80%;font:400 1em "Courier New", Courier, monospace;overflow:scroll;}
.btn{width:50%;margin:0 0 .5em 0;border-radius: 3px 3px 3px 3px;font: 700 1.2em Arial,Helvetica,Calibri,sans-serif;overflow: visible;border:1px solid #00f;color: #fff;padding: .1em;
background-image: -o-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: -moz-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: -webkit-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: -ms-linear-gradient(bottom, #2ef 0%, #02f 100%);
background-image: linear-gradient(to bottom, #2ef 0%, #02f 100%);}
</style>
</head><body>
EOT;
ob_flush();
$ndx = 1;
$js = "var contents=new Array();\ncontents[0] = '';\n";
$directory = 'users/';
$files = scandir($directory) ;
$options = "<option></option>\n";
foreach( $files as $file ){
if ( !is_dir($file) ){
if(pathinfo($file,PATHINFO_EXTENSION) == 'php' ){
$options .= "<option>$file</option>\n";
$contents = file_get_contents($directory . $file);
$contents = preg_replace('/</','<',$contents);
$contents = preg_replace('/>/','>',$contents);
$contents = preg_replace('/\n/','<br>',$contents);
$contents = addslashes( $contents);
$js .= "contents[$ndx] = \"$contents\"\n";
$ndx++;
}
}
}
echo <<<EOT
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select size="1" name="CodeList" id="CodeList" onchange="CodeChange();">
$options
</select>
<h3>Saved Codes</h3>
<form method="post" action="/evo/avsaveprocess.php"><div>
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<label>Description:</label>
<input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /><br/>
<textarea rows="10" name="Code" id="CodeValue" onload="resize()">
</textarea><br/>
<input class="btn" type="submit" value="Save" />
</div></form>
<script type="text/javascript">
//<![CDATA[
$js
sel = document.getElementById('CodeList');
txt = document.getElementById('CodeValue');
var maxHeight = (window.innerHeight - txt.offsetTop) - 40;
function CodeChange(){
txt.style.height = '100px';
var ndx = sel.selectedIndex;
var temp = contents[ndx].replace(/</g,'<');
temp = temp.replace(/>/g,'>');
txt.value= temp.replace(/<br>/g,"\\n");
var h = txt.scrollHeight;
if(h > maxHeight){h = maxHeight;}
txt.style.height = h + 'px';
}
//]]>
</script></body></html>
EOT;
ob_end_flush();
I wanted to put a checkbox autosum on my website so that anyone who check a box and submit, the values (Points) of those check box are automatically added to my total sum (on home page actually)
I have found this code so far for java script.
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td> <input name="sum_m_1" value="25" type="checkbox" id="sum_m_1" onclick="UpdateCost()"> </td>
<td> ResponseOption_1 </td>
</tr>
<tr>
<td> <input name="sum_m_2" value="15" type="checkbox" id="sum_m_2" onclick="UpdateCost()"> </td>
<td> ResponseOption_2 </td>
</tr>
</table>
<input type="text" id="totalcost" value="">
With JAVASCRIPT:
<script type="text/javascript">
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'sum_m_'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
document.getElementById('totalcost' ).value = sum.toFixed(2);
}
window.onload=UpdateCost
</script>
This will add up the values but i wanted to add by checking check boxes --> Submit --> collect the data --> add to my main total.
Any helps would be much appreciated.
Simple changes:
Add a button "calculate cost".
Removed the onclick events from the checkboxes and added the onclick event to the button instead.
Note that "window.onload=UpdateCost" is still there because what you want ideally is for the total cost to be displayed properly as 0.00 when the page loads.
HTML
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td> <input name="sum_m_1" value="25" type="checkbox" id="sum_m_1"> </td>
<td> ResponseOption_1 </td>
</tr>
<tr>
<td> <input name="sum_m_2" value="15" type="checkbox" id="sum_m_2"> </td>
<td> ResponseOption_2 </td>
</tr>
</table>
<input type="text" id="totalcost" value="">
<input type="button" value="update cost" onclick="UpdateCost();">
JavaScript
<script type="text/javascript">
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'sum_m_'+i;
elem = document.getElementById(gn);
if (elem. checked == true) { sum += Number(elem. value); }
}
document.getElementById('totalcost' ).value = sum.toFixed(2);
}
window.onload=UpdateCost
</script>
Hope that's the kind of thing you wanted, let me me know what you think.
Hi I'm trying to get a dinamically input added with Jquery, but when I try to get the code it's not working
The code in codeigniter catch all POST but less the one added by jquery
here is the code:
<script type="text/javascript">
$(document).ready(function(){
var value = parseFloat($("#subtotal").val());
$('.subtotal').html(value);
$('#subtotal').val(value);
$('input[name="phprop"]').change(function(event){
if($('input[name="phprop"]:checked').val() == 'Yes'){
$('#sections').show();
}else if($('input[name="phprop"]:checked').val() == 'No'){ $('#sections').hide();}
});
$('input[name="xsst"]').change(function(event){
if($('input[name="xsst"]:checked').val() == 'Yes'){
$('#xtraphotos').show();
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo('#xtrabox');
var num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i); i++;
}else if($('input[name="xsst"]:checked').val() == 'No'){
$('#xtraphotos').hide();
$('#xtraphotos input[type="text"]').remove();
var num = value - 9.95 * (i - 1);
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(0);
i = 1;
}
});
var scntDiv = $('#xtrabox');
var i = 1;
$('#addScnt').live('click', function() {
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo(scntDiv);
num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i);
i++;
return false;
});
});
</script>
Here is the HTML
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
Here is the Codeigniter code:
if($_POST['extrass'] !=0){
for($i=1;$i<=$_POST['extrass'];$i++){
$names = "extraid".$i;
$extras .= $_POST[$names];
if($i!=$_POST['extrass']){
$extras .= "-";
}
}
Here is the complete HTML (Just the form Section):
<?php echo form_open_multipart(base_url() . 'purchase/confirmation')?>
<p style="float:left">Image ID of the Photos for your Website</p><div style="float:left;margin: 13px 0 0 110px;width: 450px;"><?php
if($idtype == 4){$x=3;}elseif($idtype == 1){$x=5;}elseif($idtype == 2){$x=10;}elseif($idtype == 3){$x=13;}
for($i=1;$i<=$x;$i++){?><input type="text" name="ssid[]" id="ssid_<?=$i?>" value="" style="width:80px; margin-left:4px;"/><?php }?></div>
</div>
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
<br />
<div id="choose_your_template" style="background-image:url(<?=base_url()?>images/step_4.png)"><div style="padding-left:5px; float:left">
<span style=" position: relative; top: 14px; left: 210px; font-size: 18px; color: gray; ">Step 4: Do you have Photos? Upload the pictures for your website.</span></div>
</div>
<div style="margin-left: 50px;">
<label>Do you have photos of your property? </label>Yes<input type="radio" name="phprop" id="phprop" value="Yes"/>No<input type="radio" name="phprop" id="phprop" value="No"/><br />
<div id="sections" style="display:none;">
<p>Upload the photos in the theme that they should be used. The photos should be in jpge.format. Otherwise the system will not accept. them.</p><br/>
<?php
if($idtype == 4){$x=1;}elseif($idtype == 1){$x=3;}elseif($idtype == 2){$x=4;}elseif($idtype == 3){$x=5;}
for($i=1;$i<=$x;$i++){?>
<label>Section</label><select name="section[]" id="section"><option value="">Choose Section</option><option value="home">Home</option><option value="about-us">About Us</option><option value="contact-us">Contact Us</option></select><?php for($j=1;$j<=4;$j++){?><input type="file" name="userphoto<?=$i?><?=$j?>" /><?php }?><br /> <br />
<?php }?>
<p>I certify that the photos that i am uploading for the website development are of my entire property and that I have all the copyrights.</p></div>
</div><br />
<input type="hidden" id="domain" name="domain" value="<?=$domain?>" />
<input type="hidden" id="payment_plan" name="payment_plan" value="<?=$poption?>" />
<?php if($ownamedomain){?>
<input type="hidden" name="ownamedomain" id="ownamedomain" value="<?=$ownamedomain?>" />
<?php }?>
<input type="hidden" name="idtype" id="idtype" value="<?=$idtype?>" />
<input type="hidden" name="templateid" id="templateid" value="<?=$templateid?>" />
<input type="hidden" name="extrass" id="extrass" value="0" />
<input type="hidden" name="subtotal" id="subtotal" value="<?=$subtotal?>" />
<div style="padding-left:45px; padding-top:15px;">
<hr style=" width: 868px; margin: 0 0 16px; "/>
<div align="center">
<p>Subtotal: USD$<span class="subtotal"><?=$subtotal?></span> </p></div>
</div>
<div style="background:url(<?=base_url()?>images/bottombar.png) no-repeat;display: block;height: 16px;margin: 0 36px 10px;width: 902px;"></div>
<input type="submit" name="continue" id="continue"/><input type="button" value="Back" onClick="history.back();" class="back">
</div>
Your HTML have a tag form?
When.you not put forms elements inside a form, onload, some brownser add a form to correct code syntax... But when you add nes elements using DOM, maybe this elements not include inside this form...
How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.
That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>