将表中的两个单元格相乘

时间:2013-09-29 18:52:07

标签: javascript

jsFiddle:http://jsfiddle.net/KSCLC/3/

我有一个脚本(下面),它向表中添加一行。

我想要将两个单元格一起添加以获得总计

Item Price * Item Weight = Line Total 

if (field.value.length != 0) {
    var upc=document.getElementById("UPC").value;
    var weight=document.getElementById("weight").value +"lbs";
    var table=document.getElementById("ScannedItems");
    var row=table.insertRow(-1);
    var cell1=row.insertCell(0);
    var cell2=row.insertCell(1);
    var cell3=row.insertCell(2);
    var cell4=row.insertCell(3);
    var cell5=row.insertCell(4);
    var cell6=row.insertCell(5);
    cell1.innerHTML=upc;
    cell2.innerHTML="Example Description";
    cell3.innerHTML="$3.00";
    cell4.innerHTML=weight;
    var total=cell3.innterHTML*cell4.innerHTML;
    cell5.innerHTML="$" +total;
    cell6.innerHTML="<a><span class='glyphicon glyphicon-plus' style='padding-right:15px;'></span></a><span>&nbsp;</span><a><span class='glyphicon glyphicon-minus'></span></a>";
    field.value ='';
}

我尝试在两个单元格之后和新单元格之前创建一个新变量,但我得到的只是表格中的$Nan

我搞砸的具体问题是:

cell3.innerHTML="$3.00";
cell4.innerHTML=weight;
var total=cell3.innterHTML*cell4.innerHTML;
cell5.innerHTML="$" +total;

2 个答案:

答案 0 :(得分:2)

首先,您需要解析用户输入之外的整数。接下来,你需要繁殖。然后附加任何单位:

var weight = parseInt(document.getElementById("weight").value);
var price = 3;
var total = weight * price;

//

cell3.innerHTML = "$" + price.toFixed(2);
cell4.innerHTML = weight + "lbs";
cell5.innerHTML = "$" + total.toFixed(2);

根据评论进行修改

通过data-attributesgetAttribute访问setAttribute

cell5.setAttribute('data-total', total); // caches the total into data

var total = cell5.getAttribute('data-total'); // reads the value

答案 1 :(得分:0)

我只是指出错误,你可以调试

    var upc=document.getElementById("UPC").value;
    var weight=document.getElementById("weight").value +"lbs"; // here appending lbs to weight
    var table=document.getElementById("ScannedItems");
    var row=table.insertRow(-1);
    var cell1=row.insertCell(0);
    var cell2=row.insertCell(1);
    var cell3=row.insertCell(2);
    var cell4=row.insertCell(3);
    var cell5=row.insertCell(4);
    var cell6=row.insertCell(5);
    cell1.innerHTML=upc;
    cell2.innerHTML="Example Description";
    cell3.innerHTML="$3.00"; // value having $, so maths operation won't work
    cell4.innerHTML=weight; // value having lbs, so maths operation won't work 
    var total=cell3.innterHTML*cell4.innerHTML; // Is not an integer 

而不是上面你可以尝试这样的事情

   var weight=document.getElementById("weight").value;
   var table=document.getElementById("ScannedItems");
   var row=table.insertRow(-1);
   var cell1=row.insertCell(0);
   var cell2=row.insertCell(1);
   var cell3=row.insertCell(2);
   var cell4=row.insertCell(3);
   var cell5=row.insertCell(4);
   var cell6=row.insertCell(5);
   cell1.innerHTML=upc;
   cell2.innerHTML="Example Description";
   cell3.innerHTML="$3.00";
   cell4.innerHTML=weight+"lbs";
   var total=3*weight;
相关问题