Home > Blockchain >  how to get all data of price, qty from html in js and multiple it accordingly and add it into html i
how to get all data of price, qty from html in js and multiple it accordingly and add it into html i

Time:02-01

I have attached the HTML on Photo Question - how to get all data of price, qty from HTML in js and multiple it accordingly and add it into HTML in Django. anyone help me.

const x = document.getElementById("qty").innerHTML;
const y = document.getElementById("price").innerHTML;
const z = document.getElementById("total");

function calculator(qty, price) {
  let lowercase = price.toLowerCase();
  const remove_price_string = lowercase.replace("only", "");
  console.log(remove_price_string);
  let total = remove_price_string * qty;
  console.log(total);
}

calculator(x, y);

enter image description here

enter image description here

enter image description here

Models.py

CodePudding user response:

I'm going to assume that each bill is a Django model object. The easiest way to do this calculation in Django is to add it as a function to your model:

# models.py
from django.db import models
import re

class Bill(models.Model):
    full_name = models.CharField(max_length=30)
    food_name = models.CharField(max_length=30)
    qty = models.IntegerField()

    # Ideally, you would represent the price using
    # a DecimalField. 
    # price = models.DecimalField(decimal_places=2)
    # only = models.BooleanField(default=False)

    # However, you said you're using a string instead.
    price = models.CharField(max_length=20)

    # If price was a DecimalField, you could do a simple
    # calculation.
    #def total(self):
    #    return self.qty * self.price

    # However, since it's a string, you'll have to
    # convert it to a whole number first.
    def total(self):
        """Computes the total bill from the quantity and price."""
        # Remove non-numeric strings like 'only'
        # from the price. Warning: this will remove
        # decimal points too, so it only works with
        # whole numbers as prices.
        price = re.sub("[^0-9]", "", self.price)

        # Convert it to a whole number so we can do
        # math on it.
        price = int(price)

        # Return the calculated result
        return self.qty * price

You can call this function in your template by typing its name, without parentheses:

<td id="total">{{ bill.total }}</td>

Please be careful about how you represent currencies. If you need to represent fractional amounts, use a DecimalField with an appropriate number of decimal places set; otherwise, use an IntegerField. You should never use a FloatField to represent currencies, as it does not always store an exact representation of a currency amount.

  •  Tags:  
  • Related