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">
<i开发者_运维百科nput 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
<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')
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>
The concat operator in javascript is +, not .
精彩评论