I found this question to be exactly the same problem I'm facing, but the answers suggested using objects for dynamic access. This might be well and good, but I'm looking for the exact simple answer on how to include a variable in a function's name.
I'm using ClockPick and dare not mess up the code, so I can't use objects or anything else. The problem is that with [ $("#clockpick"+x).clockpick ] the result isn't [ $("#clockpick0").clockpick ] but instead [ $("#clockpick"+x).clockpick ].
This all happens inside a PHP loop and it looks something like this:
var x = 0; (declared previously outside of the loop)
<script>
function doit()
{
$("#clockpick"+x).clockpick
({
starthour: 7,
endhour: 20
...
});
}
x++;
timepicker.php
<script>var times = 0;</script>
<?php
$goo = $_POST['goo'];
for ($foo = 0; $foo < $goo; $foo++)
{
?>
<script>
function clocker()
{
$("#clockpick"+times).clockpick
({
starthour: 7,
endhour: 20
});
} times++;
</script>
<?php
print "<input type='text' id='clockpick$foo' onclick='clocker()' />
?>
As mentioned, this works ok if I manually set "times" to a number, but as you can see, I don't know what number $goo has. In all, this is still a simplified demo from the actual page of 153 rows.
1 Answer 1
You are using a javascript variable to be incremented in a php loop.
The problem is that php will just write your javascript code as is, printing $("#clockpick"+times) at each iteration of the php loop.
To achieve what you want to do, you should use $foo instead of the useless javascript variable times like this
<?php
$goo = $_POST['goo'];
for ($foo = 0; $foo < $goo; $foo++)
{
?>
<script>
function clocker()
{
<?php
print "$('#clockpick$foo').clockpick"
?>
({
starthour: 7,
endhour: 20
});
}
</script>
<?php
print "<input type='text' id='clockpick$foo' onclick='clocker()' />"
}
?>
xa PHP variable or a Javascript variable? Can you show us your PHP as well?