John Davidson

javascript - Get the product price from a element JS

0 comments
Message:


I have a script to make some calculation but i dont know
how to get price from a element check the code below




/* THE PRICE DOESNT SHOW ON THIS SNIPPET BECAUSE REQUIRES TO BE IN SAME DIRECTORY WITH FILE */

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

</div>
<div class="row">
<div class="col-3">
<label for="qty_product">qty</label>
<input type="number" value="0.01" class="qty" id="qty_product"/>
</div>
<div class="col-2">
<label for="price_product">price</label>
<input type="number" readonly value="0" id="price_product"/>
</div>
</div>


<div class="row my-4">
<div class="col-9 text-right total">
Total
</div>

<div class="col-2 total-val">
<span id="total_value">0</span
</div>
</div>

</div>

<script>
function calculateTotal()
{
let unit_price={
<!-- the price should be always * 100 -->
product: 304.36 * 100
};
let item_price={}

item_price.product = ($("#qty_product").val() * unit_price.product )
$("#price_product").val(item_price.product);

let total = item_price.product;


$("#total_value").text(total);

}

$(function()
{
$(".qty").on("change keyup",calculateTotal)
})


</script>

<!-- I WANT THE PRICE TO COME FROM THIS ELEMENT NOT FROM ONE IN THE SCRIPT* -->
<stock-market-widget type="inline" template="generic" assets="MSFT" markup="{price}" api="yf"></stock-market-widget>
<!-- I WANT THE PRICE TO COME FROM THIS ELEMENT -->

<script>
var premiumStockMarketWidgets = {
pluginUrl: '../',
assetsLogoImages: JSON.parse('<?php print json_encode($assetsLogoImages)?>')
}
</script>
<script src="../assets/dist/app.js"></script>
</body>
</html>


My Answer:
To get the product price from an element in JavaScript, you can use the following code:

javascript
function calculateTotal() {
let unit_price = {
product: parseFloat(document.getElementById("price_element").innerText) * 100
};
let item_price = {}

item_price.product = (parseFloat(document.getElementById("qty_product").value) * unit_price.product)
document.getElementById("price_product").value = item_price.product;

let total = item_price.product;

document.getElementById("total_value").innerText = total;
}

document.addEventListener("DOMContentLoaded", function() {
calculateTotal();
document.getElementById("qty_product").addEventListener("change", calculateTotal);
});


In this code, replace `"price_element"` with the id of the element that contains the product price. This code will retrieve the price from that element and use it in the calculation.

Rate this post

3 of 5 based on 2975 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us