For a customer, I want to tell them that if the price of the products in the current currency they have active is equal to zero, to change their currency and not be able to add to the shopping cart, but no matter what, I try to get the data inside the amount. Nan is coming back
My Html Code
var priceProduct = document.getElementById('itemprice').lastChild;
$('#button-cart').on('click', function() {
if(priceProduct == 0) {
//The rest of the code
} else {
//The rest of the code
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<span id="itemprice"><span >$</span>0.00</span>
</li>
</ul>
<button type="button" id="button-cart" >
<span >add To cart</span>
</button>
CodePudding user response:
In your code
var priceProduct = document.getElementById('itemprice').lastChild
.lastcChild
will always give you a DOM node, in this case a text node.
To get the text node, use node.textContent
(or node.innerText, differences are subtle).
You can then parse this to an int, to compare with 0, or you can compare with a string directly:
var priceProduct = document.getElementById('itemprice').lastChild.textContent;
$('#button-cart').on('click', function() {
if (priceProduct === "0.00") {
//The rest of the code
console.log("no cost");
} else {
//The rest of the code
console.log("cost to be calculated");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<span id="itemprice"><span >$</span>0.00</span>
</li>
</ul>
<button type="button" id="button-cart" >
<span >add To cart</span>
</button>
One issue you have here is that the value is 0.00
- parsing to an int will give 0
- if you value was actually 0.10
then parseInt("0.10")
will also give "0" - your values are decimals not ints.