It’s a complicated title, I know. I think an example would best illustrate what I mean:
Let’s say I’m asking the user for their favorite Rock albums: albumName and albumArtist. I have a table with two columns that starts out with only one row. When the user clicks a button, a javascript function adds another row with the appropriate input fields in the appropriate cells. Then all of this data is stored in a MySQL table. This all works fine.
When the user comes back, I’d like to re-render the table, inserting all of the user’s submitted values. However, when I call the same JS function using PHP <echo> it renders above the form. How can I fix this?
Sample code below:
Javascript in head:
function addInputCell(newRow, cellNum, size, maxLength, fieldID, inputID, value)
{
var newCell = newRow.insertCell(cellNum);
var elem = document.createElement('input');
elem.type = 'text';
elem.size = size;
elem.maxlength = maxLength;
elem.name = fieldID + inputID;
elem.value = value;
newCell.appendChild(elem);
alert(elem.value);
}
function add3CellRow(fieldID, size1, maxlength1, size2, maxlength2, value)
{
var table = document.getElementById(fieldID);
var lastRow = table.rows.length;
if(lastRow <22){
var newRow = table.insertRow(lastRow - 1);
var cellLeft = newRow.insertCell(0);
var textNode = document.createTextNode(lastRow - 1);
cellLeft.appendChild(textNode);
addInputCell(newRow, 1, size1, maxlength1, fieldID, 'Name[]', value);
addInputCell(newRow, 2, size2, maxlength2, fieldID, 'Artist[]', value);
}
else
{
alert('You can only enter 20 values in this field');
}
}
HTML in body:
<table width="450" border="0" id='album' cellspacing="0" cellpadding="0">
<thead>
<tr>
<td width="3"></td>
<td width="90%" align="center"><b>Album Name</b></td>
<td width="10%" align="center"><b>Album Artist</b></td>
</tr>
</thead>
<tr>
<td align="right">1</td>
<td><input type="text" size="20" name="albumName[]" maxlength="20" value='<?php echo($onfile['albumName']);?>'/></td>
<td><input type="text" size="20" name="albumArtist[]" maxlength="20" value='<?php echo($onfile['albumArtist']);?>'/> </td>
</tr>
<tr>
<td></td><td></td><td align="right"><input type="button" value="Add Concern" onClick="add3CellRow('album',20,20,20,20 ,'');"/></td>
</tr>
</table>
PHP in body:
<?php
echo ("<script type='text/javascript'>");
//Get the data in the rock table where userID matches
$result = mysql_query("SELECT * FROM rock WHERE userID = '$_SESSION[userID]'");
while($onfile = mysql_fetch_array($result)) //Set the data into an array
{
echo ("add3CellRow('rock',20,20,20,20, '$onfileConcern[albumName]');");
}
echo ("</script>");
?>
Got it. Created a PHP function that is called onLoad. Included below. Note the first entry is ignored as it is already displayed in the HTML section of the code