Search code examples
phpjavascriptdhtml

getElementById in a FOR loop not working


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

Solution

  • <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')