In a PHP file, via the ajax technique, I'm generating tables based on data from a database as shown in the following snippet:
$i = 0;
echo $dayOfWeek;
echo "<table>
<tr>
<th>Name</th>
<th>Expected Time</th>
<th>Start Time</th>
<th>End Time</th>
<th>Auto</th>
</tr>";
while ($r = $q->fetch_assoc()) {
$schedule = $r['schedule'];
$sch_arr = json_decode($schedule)->schedule;
foreach ($sch_arr as $entry) {
$day = $entry->Day;
if ($day == $dayOfWeek) {
echo "<tr>";
echo "<td>" . $r['employee_name'] . "</td>";
$stime = $entry->{'Start Time'};
$etime = $entry->{'End Time'};
$expected = $stime.'-'.$etime;
echo "<td id='exptime_".$i."'>" . $expected . "</td>";
echo "<td><input type='text' id='stime_".$i."' name='stime_'></td>";
echo "<td><input type='text' id='etime_".$i."' name='etime_'></td>";
echo "<td><input type='text' id='notes_".$i."' name='notes_'></td>";
echo "<td><button type='submit' id='autofill_".$i."'> Autofill </button></td>";
echo "</tr>";
echo "<tr><th colspan='8'><br/><hr width='100%'></th><tr>";
$i++;
}
}
}
echo "</table>";
I want the generated Autofill buttons to have functionality based on this:
<script>
$(document).ready(function() {
$("#autofill").click(function(){
var exp = document.getElementById("expected").innerHTML;
var myArray = exp.split("-");
document.getElementById("stime").value = myArray[0];
document.getElementById("etime").value = myArray[1];
});
});
</script>
So I attempted to convert that javascript code into html as shown below:
echo "<script>";
echo "\$(document).ready(function() {";
foreach (range(0, $i) as $int) {
echo "\$('#autofill_".$int."').click(function(){";
echo "var exp = document.getElementById('exptime_".$int."').innerHTML;";
echo "var myArray = exp.split('-');";
echo "document.getElementById('stime_".$int."').value = myArray[0];";
echo "document.getElementById('etime_".$int."').value = myArray[1];";
echo "});";
}
echo "});";
echo "</script>";
But the Autofill buttons functionality doesn't work. I escaped the $ thinking that may have been the issue. How can I auto generate javascript functions dynamically? Or perhaps there is a better way to enable functionality for dynamically generated buttons?