phpjavascriptloopsspry

how do I loop a php variable within a javascript script


I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.

$divkey is the variable that controls how many rows are in the form.

Original

<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>

so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?

Trying to use php

<script type="text/javascript">
<?php   for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>  
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>

Trying to use javascript

<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
    var num = i+1;  
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>

Solution

  • I'd recommend that you use a Javascript array for this type of task. Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.

    <script type="text/javascript">
    var sprytextfield = new Array();
    var numwrestler = <?php echo $wrestlerkey; ?>;
    for(var i = 0; i < numwrestler; i++){
        sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
    }
    
    var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
    </script>
    

    Be sure that your PHP variable(s) are defined in the file before you include them in your script.