I created a function that calculates the final cost of an order, and I'm trying to display it in a text box. However, the text box keeps returning "$ NaN" and I cannot find the error. I'm a very beginning student of html and js, so any explanation is appreciated.
function costCalculator() {
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value= "$ "+parseFloat(this.totalCost).toFixed(2);
document.getElementById("balance").value= "$ "+parseFloat(this.balance).toFixed(2);
}
Here's the button that calls the function and the text box that I want it to appear it:
<button id="totalSales" onclick = "costCalculator();" >Calculate Total</button>
<br><br>
<input type="text" id="finalCost" value="" size="3" readonly="true" />
You should check console log or run debugger (F12) first - lot of bugs / missing info at least in question here, but in case I put something instead of all missing items, it starts to run without code errors at least ;-)
var burgerOnePrice = 123,
burgerTwoPrice = 234,
burgerThreePrice = 345,
tip = 456,
useCard = 1;
function costCalculator() {
var totalCost = 0,
f = document.forms[0],
balance = { value: f.balance.value.replace(/[$ ]/,'') },
burgerOne = f.burgerOne,
burgerTwo = f.burgerTwo,
burgerThree = f.burgerThree;
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
f.finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
f.finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value = "$ " + parseFloat(totalCost).toFixed(2);
document.getElementById("balance").value = "$ " + parseFloat(balance.value).toFixed(2);
}
<form>
<input type="button" id="totalSales" onclick = "costCalculator();" value="Calculate Total">
<br><br>
<input name="burgerOne" value="1">
<input name="burgerTwo" value="2">
<input name="burgerThree" value="3">
<input type="text" id="finalCost" value="" size="3" readonly="true" />
<input id="balance" value="$ 100000">
</form>
Related
I have some input with 3 values - entrance price, extra (in percent), price
It calculates by the formula: input price * per percentage extra = price
Here is my code:
HTML
function sum() {
var txtFirstNumberValue = document.getElementById('enterence_price').value;
var txtSecondNumberValue = document.getElementById('extra').value;
var result = parseFloat(txtFirstNumberValue) / 100 * parseFloat(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('price').value = result.toFixed(2);
}
}
<label>Enterence Price<br></label>
<input type="text" id="enterence_price" onkeyup="sum();">
<br>
<label>extra%<br></label>
<input type="text" id="extra" value="120%" onkeyup="sum();">
<br>
<label>Price<br></label>
<input type="text" id="price" onkeyup="sum();">
<br>
Now I need when I change the value in the "Price" input - my extra value should change automatically, the entrance price should not change
This is second formula:
Extra price =(price/entrance price)*100%
Pass the this keyword into your function, so you can detect which input has been triggered.
function sum(el) {
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
let result;
if (el.id === "enterence_price" || el.id === "extra") {
result = parseFloat(entrPriceEl.value) / 100 * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "price") {
result = (priceEl.value / entrPriceEl.value) * 100;
if (!isNaN(result)) {
extraEl.value = result + "%";
}
}
}
<label>Enterence Price<br></label>
<input type="text" id="enterence_price" onkeyup="sum(this);">
<br>
<label>extra%<br></label>
<input type="text" id="extra" value="120%" onkeyup="sum(this);">
<br>
<label>Price<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
How to correctly get input data and call it in the function?
I try to call this function in submit button, but I can't see any action.
<input style="display:none;" class="form-control col-md-5 col-8" id="pesel" minlenght="11"
maxlength="11"
type="text" name="pesel"
placeholder="PESEL" required>
<p><input class="submit-button" type='submit' name='submit' value='Wyślij' onclick="isValidPesel()"></p>
<span id="error"></span>
<script>
function isValidPesel(pesel) {
function validatepesel(pesel) {
var reg = /^[0-9]{11}$/;
if (reg.test(pesel) == false) {
console.log("error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
return false;
} else {
var digits = ("" + pesel).split("");
if ((parseInt(pesel.substring(4, 6)) > 31) || (parseInt(pesel.substring(2, 4)) > 12))
return false;
console.log("Error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
var checksum = (1 * parseInt(digits[0]) + 3 * parseInt(digits[1]) + 7 * parseInt(digits[2]) + 9 * parseInt(digits[3]) + 1 * parseInt(digits[4]) + 3 * parseInt(digits[5]) + 7 * parseInt(digits[6]) + 9 * parseInt(digits[7]) + 1 * parseInt(digits[8]) + 3 * parseInt(digits[9])) % 10;
if (checksum == 0) checksum = 10;
checksum = 10 - checksum;
return (parseInt(digits[10]) == checksum);
}
}
var pesel = document.getElementById("pesel").value;
console.log(pesel);
}
</script>
This should do the trick: (No change in the HTML)
<input style="display:none;" class="form-control col-md-5 col-8" id="pesel" minlenght="11" maxlength="11" type="text" name="pesel" value="324983274823" placeholder="PESEL" required>
<p>
<input class="submit-button" type='submit' name='submit' value='Wyślij' onclick="isValidPesel()">
</p>
<span id="error"></span>
JavaScript: Error was you not calling the validatepesel function at the end.
function isValidPesel(pesel) {
function validatepesel(pesel) {
var reg = /^[0-9]{11}$/;
if (reg.test(pesel) == false) {
console.log("error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
return false;
} else {
var digits = ("" + pesel).split("");
if ((parseInt(pesel.substring(4, 6)) > 31) || (parseInt(pesel.substring(2, 4)) > 12))
return false;
console.log("Error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
var checksum = (1 * parseInt(digits[0]) + 3 * parseInt(digits[1]) + 7 * parseInt(digits[2]) + 9 * parseInt(digits[3]) + 1 * parseInt(digits[4]) + 3 * parseInt(digits[5]) + 7 * parseInt(digits[6]) + 9 * parseInt(digits[7]) + 1 * parseInt(digits[8]) + 3 * parseInt(digits[9])) % 10;
if (checksum == 0) checksum = 10;
checksum = 10 - checksum;
return (parseInt(digits[10]) == checksum);
}
}
var pesel = document.getElementById("pesel").value;
validatepesel(pesel);
}
Method 1:
<input class="submit-button" type='submit' name='submit' value='Wyślij' onclick="isValidPesel(this)">
<script>
function isValidPesel(element) {
console.log(element.value);
}
</script>
Method 2:
<input type="hidden" value="Wyślij" id="myInput">
<input class="submit-button" type='submit' name='submit' onclick="isValidPesel(this)">
<script>
function isValidPesel() {
var str = $("#myInput").val();
console.log(str);
}
</script>
I started learning JavaScript and I want to do my own small project 'BMI calculator' but I can't find an error with my if statement.
Everything working fine but if as a input I will type for example 0, I don't see any warning message instead I see result of calculation.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input id="height">
<br> Weight: <input id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>
Because you don't stop the function when you detect invalid input. You put the error message into the message panel, but then you continue to the code that performs the calculation with the invalid input.
You should return from the function after displaying the error message.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
return;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
return;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input type="number" id="height">
<br> Weight: <input type="number" id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>
I made a simple change calculator. After playing with the code, I managed to make it calculate the values I needed but I can't make it populate my form. If I use alert, the function is right but if I try to use innerHTML to fill the fields, nothing happens. I am really stuck on this one. :(
var quarters;
var dimes;
var nickels;
var pennies;
function Calculate() {
if (cents >= 25) {
quarters = Math.floor(cents / 25);
var qreminder = cents % 25;
if (qreminder <= 24) {
dimes = Math.floor(qreminder / 10);
var dreminder = qreminder % 10;
}
if (dreminder < 10) {
nickels = Math.floor(dreminder / 5);
var nreminder = dreminder % 5;
}
if (nreminder < 5) {
pennies = nreminder / 1;
}
document.getElementById("quarters").innerHTML = quarters;
document.getElementById("dimes").innerHTML = dimes;
document.getElementById("nickels").innerHTML = nickels;
document.getElementById("pennies").innerHTML = pennies;
}
if (cents < 25) {
quarters = Math.floor(cents / 25);
var qreminder = cents % 25;
if (qreminder <= 24) {
dimes = Math.floor(qreminder / 10);
var dreminder = qreminder % 10;
}
if (dreminder < 10) {
nickels = Math.floor(dreminder / 5);
var nreminder = dreminder % 5;
}
if (nreminder < 5) {
pennies = nreminder / 1;
}
document.getElementById("quarters").innerHTML = quarters;
document.getElementById("dimes").innerHTML = dimes;
document.getElementById("nickels").innerHTML = nickels;
document.getElementById("pennies").innerHTML = pennies;
}
}
var cents = document.getElementById("cents").value;
document.getElementById("calculate").addEventListener("click", Calculate);
<div id="content">
<h1>Change Calculator</h1>
<label>Enter number of cents (0-99):</label>
<input type="text" id="cents" />
<input type="button" value="Calculate" name="calculate" id="calculate" /><br />
<p> </p>
<label>Quarters:</label>
<input type="text" id="quarters" class="disabled" disabled="disabled" /><br />
<label>Dimes:</label>
<input type="text" id="dimes" class="disabled" disabled="disabled" /><br />
<label>Nickels:</label>
<input type="text" id="nickels" class="disabled" disabled="disabled" /><br />
<label>Pennies:</label>
<input type="text" id="pennies" class="disabled" disabled="disabled" /><br />
<p> </p>
Setting the .innerHTML property of <input> types will not do anything. Instead, set the .value property of those elements.
document.getElementById("quarters").value = quarters;
document.getElementById("dimes").value = dimes;
document.getElementById("nickels").value = nickels;
document.getElementById("pennies").value = pennies;
Sorry for such a noob problem - I've not found a solution after browsing many posts and I'm afraid I don't even know what question to ask - I'm trying to auto populate the 'sunits' input field to the value of the 'bunits' input, unless changed. I barely cobbled this together for some friends, and do apologize for the poor style and everything else. The code below is also the homepage at http://lootsim.com :
<div id="buyformdiv" class="fluid ">
<span id="pickingupspan" class="actionspan">Buying:</span>
<p># units to be bought:
<input id="bunits" type="number" step="1" onchange="update()"></p>
<p>
Cost per unit :
<input id="cunits" type="number" step="0.01" onchange="update()"></p>
<p>
Overhead :
<input id="cxbship" type="number" step="0.01" onchange="update()"></p>
</div>
<div id="sellformdiv" class="fluid ">
<span id="gettingridspan" class="actionspan">Selling:</span>
<p># units to be sold:
<input id="sunits" type="number" step="1" onchange="update()"></p>
<p>
selling for ($ each) :
<input id="sprice" type="number" step="0.01" onchange="update()"></p>
<p>
Frequency :
<select id="sfreq" onchange="update()">
<option value="1">Once</option>
<option value="7">Week</option>
<option value="31">Month (31 days)</option>
<option value="365">Year</option>
</select>
</p>
</div>
Javascript"
var bunits, cunits, cxb, cxbship, btotal, sunits, sfreq, sprice, net, profit;
function update() {
var bunits = document.getElementById('bunits').value;
var cunits = document.getElementById('cunits').value;
var cunits = parseFloat(cunits).toFixed(2);
var cxbship = document.getElementById('cxbship').value;
var cxbship = parseFloat(cxbship).toFixed(2);
var cxb = bunits * cunits;
var cxb = parseFloat(cxb).toFixed(2);
var btotal = parseFloat(cxb) + parseFloat(cxbship);
var btotal = parseFloat(btotal).toFixed(2);
var sunits = document.getElementById('sunits').value;
var sprice = document.getElementById('sprice').value;
var sprice = parseFloat(sprice).toFixed(2);
var sfreq = document.getElementById('sfreq').value;
var sunitxp = sunits * sprice;
var sunitxp = parseFloat(sunitxp).toFixed(2);
var salesxdays = sunitxp * sfreq;
var salesxdays = parseFloat(salesxdays).toFixed(2);
//populate numbers in results window
if (bunits > 0) {
document.getElementById('bunitsspan').innerHTML = "Buying " + bunits + " units";
document.getElementById('sunits').value = bunits;
}
if (cunits > 0) {
document.getElementById('costspan').innerHTML = "at $" + cunits + " per unit";
}
if (cxb > 0) {
document.getElementById('cxbspan').innerHTML = "Subtotal: $" + cxb;
}
if (cxbship > 0) {
document.getElementById('cxbshipspan').innerHTML = "Overhead: " + cxbship;
}
if (btotal > 0) {
document.getElementById('subtotalspan').innerHTML = "<b>Total: $" + btotal + "</b>";
}
//populate income in results span
if (sunits > 0) {
document.getElementById('sunitsspan').innerHTML = "Selling " + sunits + " units";
}
if (sprice > 0) {
document.getElementById('sellcostspan').innerHTML = "for $" + sprice + " each";
}
if (sunitxp > 0) {
document.getElementById('sunitxpspan').innerHTML = "Subtotal: $" + sunitxp;
}
if (sfreq > 0 ) {
if ((sfreq == 1) && (sprice > 0)){
document.getElementById('sellfreqspan').innerHTML = "all units";
} else if (sfreq == 7) {
document.getElementById('sellfreqspan').innerHTML = "every day for a week";
} else if (sfreq == 31) {
document.getElementById('sellfreqspan').innerHTML = "every day for a month";
} else if (sfreq == 365) {
document.getElementById('sellfreqspan').innerHTML = "every day for a year";
}
}
if (salesxdays > 0) {
document.getElementById('salesxdays').innerHTML = "Total: $" + salesxdays;
}
}