Getting NaN In Building a Simple Calculator - javascript

I'm fairly new to Javascript and I'm currently working on a simple calculator that would allow users to answer a few questions in order to calculate their total price. The price would show up in the DIV below the form. But, the issue that I'm having is that the output in the div is NaN until the last option is selected.
The code isn't perfect since I'm just testing at this point, but here's the HTML.
const looks = document.getElementById('looks');
const edits = document.getElementById('edits');
const studio = document.getElementById('studio');
const total = document.getElementById('total');
const btn = document.getElementById('btn')
looks.addEventListener('change', totalCost);
edits.addEventListener('change', totalCost);
studio.addEventListener('change', totalCost);
btn.addEventListener('click', totalCost);
function totalCost() {
total.innerText = (looks.value * 100)
+ (edits.value * 50)
+ parseInt(studio.value);
}
<div class="container">
<form action="">
<h3>How Many Looks?</h3>
<input type="number" id="looks" value="">
<h3>How Many Edits?</h3>
<input type="number" id="edits" value="">
<h3>Location:</h3>
<select name="studio" id="studio">
<option value="">On-Location</option>
<option value="100">In-Studio</option>
</select>
<h3>Total:</h3>
<div id="total"></div>
<input type="button" value="submit" id="btn">
</form>
</div>
I'd also like to implement something where the total doesn't show up until the submit button is pressed. I'd greatly appreciate any help in these matters. Thanks a lot!

You have an issue in studio.value, its come NaN for first init, you need to check your param if its number or not before do a calculation or convert it to number like below example:
const looks = document.getElementById('looks');
const edits = document.getElementById('edits');
const studio = document.getElementById('studio');
const total = document.getElementById('total');
const btn = document.getElementById('btn')
looks.addEventListener('change', totalCost);
edits.addEventListener('change', totalCost);
studio.addEventListener('change', totalCost);
btn.addEventListener('click', totalCost);
function totalCost() {
let stdValue = parseInt(studio.value);
if(isNaN(stdValue)){
stdValue = 0;
}
total.innerText = ((looks.value * 100)
+ (edits.value * 50)
+ stdValue);
}
<div class="container">
<form action="">
<h3>How Many Looks?</h3>
<input type="number" id="looks" value="">
<h3>How Many Edits?</h3>
<input type="number" id="edits" value="">
<h3>Location:</h3>
<select name="studio" id="studio">
<option value="">On-Location</option>
<option value="100">In-Studio</option>
</select>
<h3>Total:</h3>
<div id="total"></div>
<input type="button" value="submit" id="btn">
</form>
</div>
====================
Update 1:
Like Nick Parsons Suggestion, the real answer must be via set the 0 as a default option if its needed as a number...
<option value="0">On-Location</option>
So that, look when and where you need to validate and when need to setup initial value...do both to get a good code...

this way
const
myForm = document.getElementById('my-form')
, total = document.getElementById('total')
;
myForm.oninput = evt =>
{
total.textContent = (myForm.looks.valueAsNumber * 100)
+ (myForm.edits.valueAsNumber * 50)
+ (parseInt(myForm.studio.value) || 0)
}
myForm.onsubmit = evt => // beter than btn.onclick
{
evt.preventDefault() // stop form submiting
}
<div class="container">
<form action="" id="my-form">
<h3>How Many Looks?</h3>
<input type="number" name="looks" value="0" min="0">
<h3>How Many Edits?</h3>
<input type="number" name="edits" value="0" min="0">
<h3>Location:</h3>
<select name="studio" >
<option value="" selected > On-Location </option>
<option value="100" > In-Studio </option>
</select>
<h3>Total:</h3>
<div id="total"> ? </div>
<button type="submit">submit</button>
</form>
</div>

Related

I need to make calculation sheet but the calculate button not working and calculate my inputs here is my formala ((P*D)/(2*SMYS*DF*T*E))

I want to calculate this formula (PD)/(2SMYSDFT*E) but when I click calculate Botton nothing happens (ps: I am not an expert )
I put the input and then I click calculate put no answer.
I made some changes on the code but still not working . please can someone edit the code!
<body>
<label for="formulas">Choose a formula:</label>
<select name="formulas" id="formulas">
<option value="free">Pipeline Thickness</option>
</select>
<h2>Enter inputs</h2>
<label for="P">MAOP=</label>
<input type="number" id="P" name="P">
<br>
<label for="D=">Do=</label>
<input type="number" id="D" name="D" >
<br>
<label for="SMYS">SMYS=</label>
<input type="number" id="SMYS" name="SMYS">
<br>
<label for="DF">DF=</label>
<input type="number" id="DF" name="SMYS">
<br>
<label for="T">T=</label>
<input type="number" id="T" name="T">
<br>
<label for="E">E ⅉ=</label>
<input type="number" id="E" name="E ⅉ=" >
<br>
<button type="button" onclick="calculate">calculate</button>
<p id="demo"></p>
<script>
document.getElementById('calculate').addEventListener('click', function() {
var amount = document.getElementById("P").value;
var amount = +P;
var quantity = document.getElementById("D").value;
var quantity = +D;
var amount = document.getElementById("SMYS").value;
var amount = +SMYS;
var amount = document.getElementById("DF").value;
var amount = +DF;
var amount = document.getElementById("T").value;
var amount = +T;
var amount = document.getElementById("E").value;
var amount = +E;
var total = (P * D) / (2 * SMYS * DF * T * E);
document.getElementById("total").value = total;
});
</script>
</head>
</body>
</html>
</form>

Calculate the sum of dynamic cloned forms for Profit and Loss in javascript Jquery

I am trying to build a Simple Profit and Loss page for my sales. The goal is:
One row equals One client.
Add a dynamic row based on number of clients.
For each row I need to input the sale amount and cost amount, then calculate the profit for that row(client).
Calculate the sum of all rows profit.
The issue: When I add a row, the button calculates only the first DOM row and not the result of the cloned ones as well.
$(document).ready(function() {
$("#addForm").click(function() {
$("#pnl").clone().appendTo(".originalPnlDiv");
});
});
function calculate() {
var salesPnl = document.getElementsbyClassName('sale').value;
var costPnl = document.getElementsbyClassName('cost').value;
var sum = document.getElementById('total').value = salesPnl - costPnl;
}
function totalProfit() {
var totalSalesPnl = document.getElementsbyClassName('sale').value;
var totalCostPnl = document.getElementsbyClassName('cost').value;
var totalSum = document.getElementById('grandTotal').value = totalSalesPnl - totalCostPnl;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>PNL</h1>
<div class="originalPnlDiv">
<form action="" id="pnl">
<select>
<option value="customerZ">customerZ</option>
<option value="customerX">customerX</option>
</select>
<input class="sale" type="number" placeholder="sale S$">
<input class="cost" type="number" placeholder="cost S$">
<input placeholder="invoice#">
<input type="date">
<input id="total"/>
</form>
</div>
<button id="addForm">Clone</button>
<button onclick="calculate()">calculate</button>
<br>
<br>
<button onclick="totalProfit()">Total Profit</button>
<p>The totalprofit is <span id="grandTotal"></span></p>
Thanks a lot for your help, I am only two months old regarding coding.
Have a nice day
don't use id when it's not going to be unique across the page.
re-organize your logic by moving the calculate button for each line
use document.querySelector and document.querySelectorAll
$(document).ready(function() {
$("#addForm").click(function() {
$("#pnl").clone().appendTo(".originalPnlDiv");
});
});
function calculate(button) {
var form = button.closest("form");
var salesPnl = form.querySelector('.sale').value;
var costPnl = form.querySelector('.cost').value;
var sum = salesPnl - costPnl;
form.querySelector('#total').value = sum;
return sum;
}
function totalProfit() {
var parent = document.querySelector(".originalPnlDiv");
var panels = parent.querySelectorAll("#pnl")
var grand = 0;
panels.forEach(function(panel) {
grand += calculate(panel);
})
document.querySelector("#grandTotal").innerText = grand;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>PNL</h1>
<div class="originalPnlDiv">
<form action="" id="pnl">
<select>
<option value="customerZ">customerZ</option>
<option value="customerX">customerX</option>
</select>
<input class="sale" type="number" placeholder="sale S$">
<input class="cost" type="number" placeholder="cost S$">
<input placeholder="invoice#">
<input type="date">
<input id="total" />
<button onclick="calculate(this); return false">calculate</button>
</form>
</div>
<button id="addForm">Clone</button>
<br>
<br>
<button onclick="totalProfit()">Total Profit</button>
<p>The totalprofit is <span id="grandTotal"></span></p>

Getting number from user input: string is empty on submit?

I'm stuck on a problem. I'm working on an exercise that generates a random integer between 1-10. The user will submit a number from 1-10 in the input box. If a match occurs, the user will get an alert notifying them of success.
I'm stuck on getting the number from the user input. I want to log to the console the form input, but for the life of me, I cannot figure this out. I've tried changing the form type="number", type="text" and tried using parseInt().
Anything glaring in my code?
function exerciseEight() {
let input = document.querySelector("#number").value;
let button = document.querySelector("#guess");
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
button.onclick = function() {
console.log(input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
You need to get the input value when the user clicks. You're setting input and all the other variables that depend on it when the page is first loaded.
function exerciseEight() {
let button = document.querySelector("#guess");
let number = Math.ceil(Math.random() * 10);
button.onclick = function() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
console.log(number, input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
The problem is that you are calling the function when the page loads, so it gets the values from the start, and doesn't change them at runtime when user enters input. You should call the function when user clicks the button.
function exerciseEight() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
}
let button = document.querySelector("#guess");
button.onclick = exerciseEight;
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>

Javascript: Update price when quantity changes

I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!
document.getElementById("totalTicketCost").value = 0 + "." + 00;
function ticketCost()
{
var ticketCost = 5.5;
var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;
var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;
if (!isNaN(totalTicketCost))
document.getElementById("totalTicketCost").innerHTML = totalTicketCost;
}
<form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388#xyz.com">
<h1>Ticket Purchasing Form</h1>
<p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
<div class="field">
<label class="required">How many tickets would you like to purchase?</label>
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
$<span id="totalTicketCost">0.00</span>
</div>
<div id="contactInfo" style="display:none;">
<div class="field">
<label class="required">Name:</label>
<input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
</div>
<div class="field">
<label class="required">E-mail:</label>
<input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address" onblur="validateEmail()">
</div>
</div>
<hr>
<input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
</form>
<script src="event_registration.js"></script>
</body>
Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.
var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;
// Handle the precision up to >= $100
function changeCost( num ) {
var cost = new Number( parseFloat( num ) * ticketCost );
var precision = cost.toString().length === 3 ? 3 : 4;
return cost.toPrecision( precision );
}
inputTicketQuantity.addEventListener('input', function( event ) {
var value = event.target.value;
if ( !isNaN( value ) ) {
ticketInput.innerHTML = changeCost( value );
}
});
You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.
Add an event listener to you quantity field, and recalculate price.
document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
let count = this.value;
calculatePrice(count);
});
Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -
In JS:
function updateCost(count)
{
var ticketCost = 5.5;
document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}
In HTML
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
You have to call function ticketCost() on value change event of input quantity textbox
<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
Or you can add listener in JavaScript as
document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);
Add it outside your JavaScript function ticketCost()

How to display recommendations after calculating a certain result?

How do I display something like a recommendation list after a user calculate a result from the inputs? E.g having the user to key in the salaries of the family and calculating the PCI (Per capita income) and after they key in and press on the calculate button which then will trigger a list of recommendations based on the amount of PCI the family have (Maybe tables that shows different results based on different categories of PCI?)
<!DOCTYPE html>
<html>
<head>
<script src="common.js"></script>
<script>
function cal()
{
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var total = (parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
document.getElementById('total').value = total;
alert (total);
}
</script>
</head>
<body>
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" value="" placeholder="Enter your 4th family income..."/>
<input id="members" value="" placeholder="Enter the total number of family members..."/>
<br>
<button onclick="cal()"> Calculate PCI!</button>
<br>
Total: <input id="total"> </input>
</body>
</html>
You can create a hidden div that holds the data then show that div when user clicks the button
HTML:
<div id="divToShow" style="display:none;" class="table_list" >
//put your data table here
</div>
<input type="button" name="myButton" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('divToShow').style.display = "block";
}
This should get you there: Jsfiddle.
<form id="form">
<input id="number1" type="number" min="1" name="number" placholder="add value one"> +
<input id="number2" type="number" min="1" name="number" placholder="add value one">
<button>Submit</button>
</form>
var form = document.getElementById('form');
number1 = document.getElementById('number1');
number2 = document.getElementById('number2');
form.onsubmit = function() {
var total = +number1.value + +number2.value; // add + before
alert( total );
};
function cal(){
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var recommanted;
var recommandations=[
{maxpci:1000,recommandation:'first_recommandation'},
{maxpci:2000,recommandation:'second_recommandation'},
{maxpci:3000,recommandation:'third_recommandation'},
{maxpci:6000,recommandation:'fourth_recommandation'}
];
var total=(parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
if(recommandations[recommandations.length - 1].maxpci < total ){recommanted=recommandations[recommandations.length - 1].recommandation;}
else{
for (var i = 0; i < recommandations.length; i++) {
if(total <= recommandations[i].maxpci){
recommanted=recommandations[i].recommandation;break;}
}}
document.getElementById('result').innerHTML = "Your PCI : "+total+"</br>Recommandation : "+recommanted;
}
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" type="number" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" type="number" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" type="number" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" type="number" value="" placeholder="Enter your 4th family income..."/>
<input id="members" type="number" value="" placeholder="Enter the total number of family members..."/>
</br>
<button onclick="cal()"> Calculate PCI!</button>
</br>
<div id="result">
</div>

Categories