I've got a form that displays user data in php. Then I've got an input field where the qty should be inputted. Then the JS that executes calculates the total and updates the total input element.
The problem is the referencing to the relevant id element of the input. The JS I have is only referencing to the last element in the php array. So eg the id name is id="qty" . $userid
, so for example the id name will be qtyuser001, qtyuser002, qtyuser003, etc, but JS only refers to qtyuser003.
I've been struggling with this for more than a day trying different methods, I can't get it to work. Is there an alternative method I should be approaching to solve this problem?
The php code
$get2 = mysqli_query($con,"SELECT * FROM table WHERE ...");
echo '<form method="post" action="">';
while($row2 = mysqli_fetch_array($get2)) {
$userID = $row2['userID'];
$fn = $row2['FirstName'];
$ln = $row2['LastName'];
echo '<tr>';
echo '<td><input readonly name="userID[]" id="userID ' . $userID . '" value="' . $userID . '"></td>';
echo '<td>' . $fn . ' ' . $ln . '</td>';
echo '<td><input type="text" size="5" name="nrOfQ[]" id="nrOfQ' . $userID . '" onchange="calc()"></td>';
echo '<td><input readonly type="text" size="5" name="total" id="total' . $userID . '"></td>';
echo '</tr>';
}
echo '</table>';
The JS code
<script>
function calc() {
var userid = <?php echo json_encode($userID); ?>;
var myrate = <?php echo json_encode($FieldInterviewerRate); ?>;
var myqty = document.getElementById('nrOfQ' + userid).value;
myResult = myqty * myrate;
var elem = document.getElementById('total' + userid);
elem.value = myResult;
}
</script>
I don't now Javascript that well