user8120868
user8120868

Reputation:

Summing prices based on quantity

I have appended by data to my panel in the code below which displays all the necessary data.

I am trying to extract the price which is being displayed and multiply by the quantity(the value that will be entered).

The problem is when i alert the price like in the code i get NaN although it is a number.

$(".container").append(
    '<p id="name">Drug: '+  drug.name + '</p> <p id="price">Drug Price  :  '+drug.price+'</p>

    <input type="text"  onKeyUp="multiply()" id="qty"  name="qty" />

    <p id="total">Total Price  $:'+0+'  </p>');  

function multiply()
{
    a = Number(document.getElementById('qty').value);
    b = Number(document.getElementById('price').value);
    c = a * b;

    document.getElementById('total').value = c;

    alert('this' + b);

}

Upvotes: 1

Views: 71

Answers (2)

DBS
DBS

Reputation: 9959

The element <p id="price">Drug Price : '+drug.price+'</p> doesn't contain a value attribute since it's a paragraph element.

I've swapped over lots of the code to JQuery since you're already using it, and used data- attributes to handle the values which lets you store them without having to extract from the elements content.

var drug = {"name":"test", "price":"100"};

// In the appended content, I've added a "data-price" attribute to the price element 
// and a span to the total to make the final print out simpler
$(".container").append(
  '<p id="name">Drug: ' + drug.name + '</p>'+
  '<p id="price" data-price="'+drug.price+'">Drug Price  :  ' + drug.price + '</p>'+
  '<input type="text"  onKeyUp="multiply()" id="qty"  name="qty" />'+
  '<p id="total">Total Price  $:<span></span></p>');

function multiply() { 
  a = Number($('#qty').val());
  // Here we access the data attribute
  b = Number($('#price').data("price"));
  c = a * b;

  // Printing out the final value into the span we added earlier
  $("#total span").text(c);

  alert("Total = " + c);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

Upvotes: 2

tiborK
tiborK

Reputation: 385

Since you already using jQuery here is the code:

Use onkeyup="multiply(drug.price, this.value)"

function multiply(a,b){
   var c = a * b;
   document.getElementById('total').value = c;
}

Please note that id has to be uniqe within the document (You can use class if you have multiple, same elements ) and declare the javaScript variables properly.

Hope that helps.

Upvotes: 1

Related Questions