Forum Moderators: open

Message Too Old, No Replies

JS Beginner needs to update table values by row

Know very little JS, but need to get this done

         

roguemouser

4:39 pm on Mar 10, 2017 (gmt 0)

5+ Year Member



Hi.

I know only the basics of JavaScript, and I'm having trouble understanding how to update a vale in a single row of a table.

I've got a PHP script that outputs a table. Each row has a hidden product id, product name, dropdowns for sizes and retail/wholesale, quantity, prices and an add to cart button. I want to add a cell that will display the total for a given row when a quantity is selected. For example, if a person selects three of product A at $10 each, the cell would immediately update with a total of $30.

I know to use innerHTML() to replace values. What I'm not sure on is how to have only the values of the one specific row the customer is selecting from updated without changing any other values in other rows.

Can someone here help me understand how this can be done?

NickMNS

6:06 pm on Mar 10, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You probably want to use jQuery for something like this. Its simplifies picking elements from the DOM.

So you can get the value of form fields with
var qty = $('input[name=quantity]').val();

Do the same for price and whatever other features. Then once you have assigned all the variables:
 $('#output').html( 'Total = ' + (qty * price));


The only other thing you need to decide on, is what event to use to trigger the calculation, like when "calculate" button is clicked.

Here is an example on fiddle:
[jsfiddle.net...]

robzilla

7:54 pm on Mar 10, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You'll probably want to attach an onChange event listener to your quantity <select> with a function that takes its value, locates the "price" column of that product's row and multiplies it by the quantity, and then puts that value in the "total" column. You can traverse/search the DOM in a bunch of ways. You could use class names or dataset attributes combined with the product ID to find and update the relevant fields, or walk up the DOM to the parent row (<tr>) and use the class names of the columns (e.g. "price", "quantity", "total") to locate the fields you want to use or update.

If this is the only functionality you need, jQuery would certainly be overkill as this can just as well be achieved with "vanilla" Javascript. I didn't give a code sample because I'm a little fuzzy on what your table looks like exactly.