0

I'm trying to get my addItem to read the data from another one and then write it back to the dom. It all works fine with one variable at a time, but not when I try and concat or append them together. After the append or concat function the variable listAdd reads as "[object text] [object text]" in firebug. when it should just read as a one value.

// calculates price
function calcPrice() {
  var price = document.getElementById("price").value;
  var quantity = document.getElementById("quantity").value;           
  var total = price * quantity;
  return total;
};

// adds item to dom
document.getElementById("add").onclick = function addItem(){
  var newItem = document.getElementById("item").value;
  var li=document.createElement("li");            
  var item = document.createTextNode(newItem);
  var total = document.createTextNode(calcPrice());
  var listAdd = item + total;
  li.append(listAdd);
  $("receipt").appendChild(li);
};

// removes last li element from ul
document.getElementById("remove").onclick = function removeItem(){
  $("li:last-child").remove();
};
4

2 回答 2

0

Your problem is here:

var item = document.createTextNode(newItem);
var total = document.createTextNode(calcPrice());
var listAdd = item + total;

You're adding together two objects. When you convert an object to a string, you typically get something like "[Object object]". You're performing this conversion on both objects, and concatenating the resulting strings.

You've tagged this question with jQuery, and actually used jQuery for parts of it. If you want to use jQuery, then use jQuery:

$('#add').click(function () {
  var newItem = $('#item').value();
  var li = $('<li/>');
  li.text(newItem + calcPrice());
  $("receipt").append(li);
});
于 2013-10-21T19:19:29.570 回答
-1

value of input box is always returned as type string, to perform arithmetic operations you must cast it to preper number so that you can perform

Try this

function calcPrice() {
var price = parseInt(document.getElementById("price").value,10);
var quantity = parseInt(document.getElementById("quantity").value,10);           
var total = price * quantity;
return total;
};

and change

var newItem = parseInt(document.getElementById("item").value,10);
于 2013-10-21T07:04:48.980 回答