views:

55

answers:

3

I'm not sure why this isn't working.

I have a record list of text fields in a form:

<input type="text" id="x1_Order">
<input type="text" id="x2_Order">
<input type="text" id="x3_Order">
<input type="text" id="x4_Order">
<input type="text" id="x5_Order">
...
<input type="text" id="x253_Order">
<input type="text" id="x254_Order">
<input type="text" id="x255_Order">

$NumberOfTotalRecords = 255

And using this PHP/Javascript:

<a href="#" onclick="for(i=0;i<=<?= $NumberOfTotalRecords ?>;i++){document.getElementById('x' . i . '_Order').value=i;}">Function</a>

When I click the Function link to trigger the javascript, in Google Chrome Developer Javascript Console, I get this error:

Uncaught SyntaxError: Unexpected string
+2  A: 
<a href="#" onclick="for(i=0;i<=<?= $NumberOfTotalRecords ?>;i++){document.getElementById('x' . i . '_Order').value=i;}">Function</a>

The . operator is string concatenation in php. Try using the + operator for string concatenation in javascript.

document.getElementById('x' + i + '_Order')
drawnonward
Thanks, it worked. Plus I needed to change the starting number for(i=0; to for(i=1; since the first id is x1_Order, not x0_Order
Level1Coder
A: 

The concat operator in javascript is +, not .

Evan Trimboli
+2  A: 

Best way to do it as follws

<script type="text/javascript">    
    function abc() {
      for(i=1;i<=<?= $NumberOfTotalRecords ?>;i++){
        document.getElementById('x'+i+'_Order').value=i;
      }
    }
</script>

   <a href="#" onclick="abc()">Function</a>
Salil