4

I am trying to create an onchange/oninput listener in my table to multiply the price and the ordered quantity to display in the total cost column. The data is being brought in through an SQL database. The PHP section might have an error that I can't identify.

<script type="text/javascript">             
function Multiply(f){
    var myBox1 = document.getElementById('editedvalues[]').value; 
    var myBox2 = document.getElementById('price').value;
    var result = document.getElementById('result'); 
    var myResult = myBox1 * myBox2;
    result.value = myResult;
    }
  }
 </script>

$sql = "SELECT item_price.item_id, item_price.ITEM_NAME,suggested_qty,Price_item
FROM item_price JOIN suggested_item  
ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>

<form action="#" method="post">
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Order Quantity</th>
<th>Total Cost ($)</th>

</tr>

<?php
while ($row = $result->fetch_assoc()) 
{
    echo "<tr>";
    echo "<td>" . $row['item_id'] ."</td>";
    echo "<td>" . $row['ITEM_NAME'] . "</td>";
    echo "<td>" . $row['suggested_qty'] . "</td>";
    echo "<td>" . $row['Price_item'] . "</td>";
    echo "<td><input type='text' name='editedvalues[]' value='" . $row['suggested_qty'] . "' oninput="Multiply()" /></td>";
    echo "<td><input name='result' /></td>";
    echo "</tr>";
}
    ?>

</table>                
</form>
0

2 Answers 2

1

You are calling input by its Id but in your form, you are indicating names only. Another thing is that you set your function to receive a variable/parameter (f) which was never mentioned in your computation.
Try this fix

<script type="text/javascript">             
function Multiply(){
    var myBox1 = document.getElementById('editedvalues[]').value; 
    var myBox2 = document.getElementById('price').value;
    var result = document.getElementById('result'); 
    var myResult = myBox1 * myBox2;
    result.value = myResult;
    }
  }
 </script>

$sql = "SELECT item_price.item_id, item_price.ITEM_NAME,suggested_qty,Price_item
FROM item_price JOIN suggested_item  
ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>

<form action="#" method="post">
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Order Quantity</th>
<th>Total Cost ($)</th>

</tr>

<?php
while ($row = $result->fetch_assoc()) 
{
    echo "<tr>";
    echo "<td>" . $row['item_id'] ."</td>";
    echo "<td>" . $row['ITEM_NAME'] . "</td>";
    echo "<td>" . $row['suggested_qty'] . "</td>";
    echo "<td><input type='text' id='price' value=" . $row['Price_item'] . "/></td>"; ?>
    <td><input type='text' id='editedvalues[]' value="<?php echo $row['suggested_qty']; ?>" oninput="Multiply()"/></td>
   <?php echo "<td><input type='text' id='result'/></td>";
    echo "</tr>";
}
    ?>

</table>                
</form>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. That does solve the problem for referencing the correct ID in the multiply function. However, I am getting an error in the echo line that calls the Multiply function. Is there a way to use the oninput call without the syntax error?
@group15 updated my answer. you can that one and check if it works
I am still getting an error in the multiply line saying "unexpected <", I appreciate your help. Any other ideas?
Still no luck, getting the same error. Is there another way incorporate the javascript function inside the line of php?
No more errors! :) Everything is coming up, can't seem to get the total cost to output, just outputting a blank field. Your help has been greatly appreciated!
|
1

I going to guess that you are getting an unexpected < error, because while the opening tag <?php is missing from your copy-paste snippet, its probably there in your actual code, and that you are directly writing your javascript snippet without enclosing it in an echo. Or, otherwise moving it outside of the php tags <?php ?>. You've also got additional javascript closing tags.

Instead of:

<?php
<script type="text/javascript">             
function Multiply(){
    var myBox1 = document.getElementById('editedvalues[]').value; 
    var myBox2 = document.getElementById('price').value;
    var result = document.getElementById('result'); 
    var myResult = myBox1 * myBox2;
    result.value = myResult;
    }
  }
 </script>

$sql = "SELECT item_price.item_id, item_price.ITEM_NAME,suggested_qty,Price_item
FROM item_price JOIN suggested_item  
ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>

Try this:

<script type="text/javascript">             
    function Multiply() {
        var myBox1 = document.getElementById('editedvalues[]').value; 
        var myBox2 = document.getElementById('price').value;
        var result = document.getElementById('result'); 
        var myResult = myBox1 * myBox2;
        result.value = myResult;
    }
</script>

<?php
$sql = "SELECT item_price.item_id,
               item_price.ITEM_NAME,
               suggested_qty,
               Price_item
        FROM item_price
        JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME;";
$result = $conn->query($sql);
?>

Moreover, I'd like to introduce you to the complex curly syntax {} approach to string representation. It can often make it much easier, for code-readability, to reference your variables between curly braces like this; note: only works between double quotes.

while ($row = $result->fetch_assoc()) 
{
    echo "<tr>";
    echo "<td>{$row['item_id']}</td>";
    echo "<td>{$row['ITEM_NAME']}</td>";
    echo "<td>{$row['suggested_qty']}</td>";
    echo "<td>{$row['Price_item']}</td>";
    echo "<td><input type='text' name='editedvalues[]' value='{$row['suggested_qty']}' oninput='Multiply()' /></td>";
    echo "<td><input name='result' /></td>";
    echo "</tr>";
}

After reviewing what it is you're trying to do, I would recommend firstly, that it's not considered good practice to mix two languages. None the less, lets roll with it. There's one critical thing which you haven't addressed yet. You are using static ID references, yet you are (potentially) outputting numerous rows. You would unfortunately end up running your javascript against the same inputs, rather than the row I imagine you are trying to target.

You would need to make them dynamic references, or alternatively, simply name them uniquely. Here's an example of how you could approach this problem:

<?php
# the SQL query
$sql = "SELECT item_price.[item_id] as itmId,
               item_price.[ITEM_NAME] as itmName,
               [suggested_qty] as itmQty,
               [Price_item] as itmPrice
        FROM item_price
        JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME;";

# execute the query
$query = $conn->query($sql);
$items = $query->result();
?>

<script type="text/javascript">
    function Multiply(itemId) {
        var itemQty = document.getElementById('itemQty'+itemId).value;
        var itemPrice = parseInt(document.getElementById('itemPrice'+itemId).innerText);
        var cost = itemQty * itemPrice;
        document.getElementById('itemCost'+itemId).innerText = cost;
    }
</script>

<form action="#" method="post">
    <table>
        <thead>
            <tr>
                <th>Item ID</th>
                <th>Item Name</th>
                <th>Item Price</th>
                <th>Suggested Quantity</th>
                <th>Order Quantity</th>
                <th>Total Cost ($)</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
            <tr>
                <td><?php echo $item->itmId; # item id ?></td>
                <td><?php echo $item->itmName; # item name ?></td>
                <td id="itemPrice<?php echo $item->itmId; ?>"><?php echo $item->itmPrice; # item price ?></td>
                <td><?php echo $item->itmQty; # suggested qty ?></td>
                <td><input type="text"
                           id="itemQty<?php echo $item->itmId; ?>"
                           value="<?php echo $item->itmQty; ?>"
                           oninput="Multiply('<?php echo $item->itmId; ?>')"></td>
                <td id="itemCost<?php echo $item->itmId; ?>"></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</form>

UPDATE:

Sure, you can use curly syntax like this:

<tbody>
    <?php
    foreach ($items as $item) {
        echo "<tr>
            <td>{$item->itmId}</td>
            <td>{$item->itmName}</td>
            <td id='itemPrice{$item->itmId}'>{$item->itmPrice}</td>
            <td>{$item->itmQty}</td>
            <td><input type='text'
                    id='itemQty{$item->itmId}'
                    value='{$item->itmQty}'
                    oninput='Multiply(\"{$item->itmId}\")'></td>
            <td id='itemCost{$item->itmId}'></td>
            </tr>";
    }
    ?>
</tbody>

4 Comments

This works great! Only thing is, the multiply function using the "complex curly syntax suggestion" isn't working? Any suggestions?
The curly syntax is a PHP thing; it doesn't apply to Javascript, if thats what you mean.
Yes, I was able to use the curly syntax and get an output. Using the final code you posted, I couldn't get it to be functional. Is there a way to use the curly syntax in combination with the javascript function?
Yes, escape the double quotes: \" --- i've updated my answer to demonstrate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.