0

I'm working on an exercise where we have to build a shopping cart using HTML and JavaScript.

After adding each row dynamically and after the user enters the amount of each medicament he want to buy, the amount provided in each row will be multiplied by the specified price. Then the total is calculated.

The HTML code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Drug Shopping Cart</title>
  <script type="text/javascript" src="drugShoppingCart.js"></script>
</head>
<body>

  <h1 style="text-align:center">Drug shopping cart</h1>
  <h2 style="text-align:center">Please enter your age & weight then choose what medicaments you want to buy to calculte the total price.</h2>
  <div style="text-align:center">
    <input type="text" value="Age" id="getAge" />
    <input type="text" value="Weight" id="getWeight" /> 
  </div>
  <br />
  <div style="border:groove; border-color:#006; background-color:rgb(0,51,153); color:rgb(255,255,255)">

  <table cellspacing="50" id="shopTable" align="center">
    <th>Drug Name</th>
    <th>Price</th>
    <th>Amount</th>
    <th>Allergic</th>
    <th>Amount of drug per item</th>
    <th>Daily dose</th>
 </table>

 <br />
 <input type="button" value="Add a new item" onClick="addTable()">  &nbsp;&nbsp;<button onclick="calculate()">Calculate</button>
 <br />
 </div>

</body>
</html>

The script is as follows:

var prices = ['', 5, 10, 15, 20];
var amntOfDrg = ['',"500mg", "250mg", "1mg", "0.5mg"];
var i=0;  //Global counter - counts the number of rows
var cell2;
var cell4;
var cell5;
var cell6;
var age=document.getElementById("getAge");
var weight=document.getElementById("getWeight");
var weight;

var dropDown;

  function selectChange(selection) {
  cell2.innerHTML = prices[selection.selectedIndex];

  if(selection.selectedIndex == 2 || selection.selectedIndex==3)
  cell4.innerHTML= "<input type='checkbox' name='Allergic' value='yes' checked onclick='return false'>";
  else
  cell4.innerHTML=" <input type='checkbox' name='Allergic' value='no' unchecked onclick='return false'>";

  cell5.innerHTML= amntOfDrg[selection.selectedIndex];


}

function addTable(){
    i++;

var table=document.getElementById("shopTable");
{


    var row = table.insertRow(1);
    var cell1= row.insertCell(0);
        cell2= row.insertCell(1);
    var cell3= row.insertCell(2);
        cell4= row.insertCell(3);
        cell5= row.insertCell(4);
        cell6= row.insertCell(5);

        cell1.innerHTML= "<select id=\"selectMenu\" " +
           "onchange=\"selectChange(this)\">" +
           "<option value=''>Select a drug:</option>" +
           "<option value='1'>Paracetamol</option>" +
           "<option value='2'>Ibuprofen</option>" +
           "<option value='3'>Saxagliptin</option>"+
           "<option value='4'>Liraglutide</option>"+
           "</select>";

           cell3.innerHTML= "<input type='text' id='amount' value='Enter the amount here' />";
}

}

function calculate(){

var table=document.getElementById('shopTable');


     }

The calculation should be performed in the calculate() function.

Do you have an idea about how can we perform this calculation by accessing all the inputs of amount?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • What is your question? – Mouser Dec 29 '14 at 20:06
  • That is not the best way to do it. You should add the values to a array and add the values in that instead. – NatureShade Dec 29 '14 at 20:07
  • I edited the post.. the question is how can we perform the calculation ? – tugce kahraman Dec 29 '14 at 20:08
  • 1
    Easy, loop over your data structure (in this case, it's an html table... probably not the best idea), for each record calculate a total record price, then add that total to an overall total. – Kevin B Dec 29 '14 at 20:10
  • Yes, this one should be performed by a loop for sure. The problem with me is the usage of the table, i mean how can i loop into the cells to get each values ? i have to access them all. do you know the procedure to access the cells ? – tugce kahraman Dec 29 '14 at 20:14

3 Answers3

1

Since this is an exercise,

You could just give a class to your cells where the price is contained. Then you can just grab all the cells with that class and loop over them

So a cell containing a price would become e.g:

<td class="priceCell">19.90</td>
<td class="priceCell">29.90</td>
<td class="priceCell">9.90</td>

Then your script becomes:

var priceCells = document.getElementsByClassName("priceCell"); //returns a list with all the elements that have class 'priceCell'

var total=0;

//loop over the cells array and add to total price 
for (var i = 0; i < priceCells.length; i++) {
    var thisPrice = parseFloat(priceCells[i].innerHTML); //get inner text of this cell in number format
    total = total + thisPrice; 
};

total = total.toFixed(2); //give 2 decimal points to total - prices are, e.g 59.80 not 59.8
alert(total);

Just for the record:

  • innerHTML returns the HTML as the name suggest of that cell - there's also innerText you could use, but it's not supported in all browsers so I used this instead.

  • Calculating prices like this is plain wrong - There are myriads of reasons why this should not be done on the client-side and in the way I suggested, but I certainly won't go over them in this answer

Community
  • 1
  • 1
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • Thank you for your contribution :). The code is pretty fine! But the problem here is that i don't have different classes for each . These ones are added dynamically. The code of imnancysun worked well so far. – tugce kahraman Dec 29 '14 at 22:07
1
function calculate(){
var table=document.getElementById('shopTable');
var count = table.getElementsByTagName('tr').length;
if (count > 0)
  {
    var total = 0;
    for(var i = 1; i < count; i++)
      {
        total += table.rows[i].cells[1].innerHTML * table.rows[i].cells[2].children[0].value;
      }
  }

alert(total);
}
imnancysun
  • 612
  • 8
  • 14
0

Work it out from the inside out. First, you need to be able to take a single record and calculate a total. This means, getting a single table row, getting the quantity and price, and multiplying them together.

var record = document.getElementById('shopTable').rows[0];
var quantity = parseInt(record.cells[2].children[0].value, 10);
var price = parseFloat(record.cells[1].innerHTML);
var recordTotal = quantity*price;

Next step would be to implement this into a loop that does the same for each record in the data structure, and then finally rounds the result off to two decimal places.

var records = document.getElementById('shopTable').rows, i, total = 0, quantity, price;

for (i = 0; i < records.length; i++) {
    quantity = parseInt(records[i].cells[2].children[0].value, 10);
    price = parseFloat(records[i].cells[1].innerHTML);
    total += quantity * price;
}

total = total.toFixed(2);

Runnable Example:

var records = document.getElementById('shopTable').rows, i, total = 0, quantity, price;

for (i = 0; i < records.length; i++) {
    quantity = parseInt(records[i].cells[2].children[0].value, 10);
    price = parseFloat(records[i].cells[1].innerHTML);
    total += quantity * price;
}

total = total.toFixed(2);

document.getElementById('result').innerHTML = total;
#result {
  color: green;
}
<table id="shopTable">
    <tr>
        <td>name...</td>
        <td>2.56</td>
        <td><input type="text" value="1" readonly /></td>
    </tr>
    <tr>
        <td>name...</td>
        <td>6.52</td>
        <td><input type="text" value="3" readonly /></td>
    </tr>
     <tr>
        <td>name...</td>
        <td>5.26</td>
        <td><input type="text" value="0" readonly /></td>
    </tr>
</table>
<span id="result">n/a</span>
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Just keep in mind that the calculated price here should NOT be sent to the server, the server should of course calculate the price taking only the quantities from the client. – Kevin B Dec 29 '14 at 20:37
  • Thank you very much. I had some problems understanding the concept of linking JavaScript codes with tables or manipulating the table data by JavaScript. your explanation worked well so far :). RESPECTS. – tugce kahraman Dec 29 '14 at 22:04