this is my code to create table with php by looping ..i want to add an onclick function in each ..so that on clicking a particular cell the background color is changed..but m getting an error. m i doing something wrong ??
<head>
<script>
function changeColor(elem)
{
elem.style.background = "red";
}
</script>
</head>
<body>
<?php
$rows = 10; // define number of rows
$cols = 4;// define number of columns
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td onclick=\"changeColor(this)\" > ".$tr." ".$td."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
Your echo
statement does not escape the quotes
echo "<td onclick="changeColor(this)" > ".$tr." ".$td."</td>";
change to this:
echo echo "<td onclick='changeColor(this)'> $tr $td </td>";
One thing PHP replaces variables with their values when they are placed inside double quotes. So you do not need any concantenation when your using variables inside double quotes
You missed escaping the quotes. It should be:
echo "<td onclick=\"changeColor(this)\" > ".$tr." ".$td."</td>";
Or you can use single quotes for the onclick
attribute:
echo "<td onclick='changeColor(this)' > ".$tr." ".$td."</td>";
you can try this
for($td=1;$td<=$cols;$td++)
{
?>
<td onclick="changeColor(this)" ><?php echo $tr." ".$td;?></td>
<?php
}
seprate html from php code