Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a Javascript function within a row in a foreach loop. I'd like to have it repeat each row and have tried this code. Each row has a element ID baserate which will be converted using the code below.

My problem is that it works only on the first row and doesn't for the rest. I do need some help to solve this, and any help is appreciated.

PHP:

foreach ($alllocs as $allrows) - no need to put complete code here.

JAVASCRIPT:

<script>     
  for (var i = 0; i < <?php echo $alllocs; ?>.length; i++) { 
    var a = document.getElementById("baserate").value;
    var e = Number(a).toFixed(2); 
    var b = Number(forex.rates.KRW).toFixed(2); 
    var c = e * b;     
    document.getElementById("welkomet").innerHTML = (c).toFixed(2);
  }  
</script> 
share|improve this question
1  
$alllocs contains an array of PHP objects and you want to access the $alllocs in Javascript? Is that what you meant? –  Aprian 20 hours ago
    
You may want to look at json_encode($value) which converts $value to JSON representation, and JSON.parse(text) which converts JSON text to Javascript Object –  Aprian 20 hours ago

1 Answer 1

I consider your foreach loop is like this

foreach ($alllocs as $allrows)

where You should replace $alllocs with $allrows in javascript code so the code be like this

<?php
foreach ($alllocs as $allrows){
...
...
?>
<script>     
  for (var i = 0; i < <?php echo $allrows; ?>.length; i++) { 
    var a = document.getElementById("baserate").value;
    var e = Number(a).toFixed(2); 
    var b = Number(forex.rates.KRW).toFixed(2); 
    var c = e * b;     
    document.getElementById("welkomet").innerHTML = (c).toFixed(2);
  }  
</script> 
<?php
...
...
}
?>

cause $alllocs is an array(not a single value)

check this general form of foreach loop

foreach (array_expression as $value){
    statement
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.