Javascript - Input Value NaN - javascript

Im new to Javascript and i was doing some DOM maniputalion, and i tried to create the BMI (body mass index) calculator, which is bodyMass / ( bodyWeight * bodyWeight ).
Then i've done some code:
HTML:
var bodyMass, bodyWeight;
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
document.getElementById("check").onclick = function() {
alert(BMI);
}
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>

You need to calculate the body mass index when the button is clicked, not on page load. By not placing your code inside the event handler, you are calculating everything before any values are entered.
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
<script>
var bodyMass, bodyWeight;
document.getElementById("check").onclick = function() {
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
alert(BMI);
}
</script>
To make sure the value is not NaN before alerting, you use isNaN.
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
<script>
var bodyMass, bodyWeight;
document.getElementById("check").onclick = function() {
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
if(!isNaN(BMI)){
alert(BMI);
} else {
alert("Please enter two valid numbers!");
}
}
</script>

You are getting the values of bodyWeigt and bodyMass even before the button is clicked, at this stage (after parseInt-ing them) they are of course not a number (NaN).
Grab the values on click of the button i.e when the user has (hopefully) entered some valid values...
document.getElementById("check").onclick = function() {
var bodyMass, bodyWeight;
bodyMass = parseInt(document.getElementById("bodyMass").value);
bodyWeight = parseInt(document.getElementById("bodyWeight").value);
var BMI = bodyMass / (bodyWeight * bodyWeight);
alert(BMI);
}
<input type="number" placeholder="Body Mass" id="bodyMass">
<input type="number" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>

Because your input are numeric, you should instead do
<input type="number" placeholder="Body Mass" id="bodyMass">
<input type="number" placeholder="Body Weight" id="bodyWeight">
and place the calculation inside the button click event, else the calculation will get executed once the page loads and you will get a NaN alert.

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>

Need help creating a working HTML form that calculates ROI

I'm trying to create an HTML form that has the user type in expected gain and cost into the input box, click calculate, and the form should calculate and display the net profit and ROI.
So far the form lets me input expected gain and cost, but the calculate button doesn't display the net profit and ROI in the appropriate boxes.
This is what I have so far (only relevant portions included):
// Declare variables
var projectName; // Gets user input for project name
var expectedCost; // Gets user input for cost of project
var expectedGain; // Gets user input for expected gain
var netProfit;
var returnOnInvestment;
function calcNetProfit() {
netProfit = expectedGain - expectedCost; // Calculate net profit
}
function calcReturnOnInvestment() {
returnOnInvestment = netProfit / expectedCost * 100; // Calculate Return on Investment
}
<form>
<label>Project Name</label>
<input>
<br><br>
<label>Cost</label>
<input>
<br><br>
<label>Gain</label>
<input>
<br><br>
<label>Net Profit</label>
<input>
<br><br>
<label>ROI as percentage</label>
<input>
<br><br>
<input type="button" name="calculate" value="Calculate" onclick="calcNetProfit(); calcReturnOnInvestment();"/><br />
</form>
Try to get the value of input type using: document.getElementById("demo").value,
and you can also manipulate the input box using the same line of code:
function calc() {
var projectName = document.getElementById("name").value
var expectedCost = document.getElementById("cost").value
var expectedGain = document.getElementById("gain").value
var netProfit = expectedGain - expectedCost;
document.getElementById("netprofit").value = netProfit;
var returnOnInvestment = netProfit / expectedCost * 100;
document.getElementById("roi").value = returnOnInvestment;
}
<form>
<label>Project Name</label>
<input type="text" id="name">
<br><br>
<label>Cost</label>
<input type="text" id="cost">
<br><br>
<label>Gain</label>
<input type="text"id="gain">
<br><br>
<label>Net Profit</label>
<input type="text" id="netprofit">
<br><br>
<label>ROI as percentage</label>
<input type="text" id="roi">
<br><br>
<input type="button" name="calculate" value="Calculate" onclick="calc();"/><br />
</form>
You are missing the steps on how to get the values for the gain, costs, and net profit.
Read on JavaScript DOM.
Here's the answer in a nutshell.
function calcNetProfit() {
var expectedGain = document.getElementById('gain').value;
var expectedCost = document.getElementById('cost').value;
var netProfit = expectedGain - expectedCost;
document.getElementById('netprofit').value = netProfit;
return netProfit;
}
function calcReturnOnInvestment() {
var expectedCost = document.getElementById('cost').value;
var netProfit = calcNetProfit();
var roi = netProfit / expectedCost * 100; // Calculate Return on Investment
document.getElementById('roi').value = roi;
}
<html>
<form>
<label>Project Name</label>
<input>
<br><br>
<label>Cost</label>
<input id="cost">
<br><br>
<label>Gain</label>
<input id="gain">
<br><br>
<label>Net Profit</label>
<input id="netprofit">
<br><br>
<label>ROI as percentage</label>
<input id="roi">
<br><br>
<input type="button" name="calculate" value="Calculate" onclick="calcNetProfit(); calcReturnOnInvestment();" /><br />
</form>
</html>
to get input value you must use
var projectname = document.querySelector('//id
or class of input id
mustbe #idname and class .classname').value;
and then manipulate with thouse values
also input tag must have type and class or id
<input type="number" class="classname">

how can i fix my javascript calculation which is not working?

the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.
You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>

Displaying content of form input element in another field using javascript onFocus event

PROBLEM: I want Javascript to calculate the sum of two numeric inputs from a user and display the sum in the third field immediately the user tabs into or clicks on the field.
ERROR: Firefox, Chrome and Safari all display zero when the third field is on focus; however, in fairness to Firefox, it reluctantly displays the required result after refreshing; others don't. I suspect an error in my code which I cannot identify, please help.
window.onload = function() {
var input1 = document.getElementById('bk').value;
var input2 = document.getElementById('softw').value;
input1 = Number(input1); // convert input to number
input2 = Number(input2);
input3 = input1 + input2; // Sum the inputs
document.getElementById('total').onfocus = function() {
document.getElementById('total').value = input3;
return input3;
}
}
<html>
<body>
<div id='fm_div'>
<form action="#" method="GET" id='form1'>
<p>Qty of Books:
<input type="text" name="bkqty" id='bk'>
</p>
<p>Qty of Software:
<input type="text" name="software" id='softw'>
</p>
<p>Total:
<input type='text' id='total'>
</p>
<p>
<input type='submit' value='send' id='submit'>
</p>
</form>
</div>
</body>
</html>
You are setting input1 and input2 on window load function. But the textboxes will not have any value on load. change your window.onload function as below
window.onload = function() {
document.getElementById('total').onfocus = function() {
var input1 = document.getElementById('bk').value;
var input2 = document.getElementById('softw').value;
input1 = Number(input1); // convert input to number
input2 = Number(input2);
input3 = input1 + input2; // Sum the inputs
document.getElementById('total').value = input3;
return input3;
}
}
<div id='fm_div'>
<form action="#" method="GET" id='form1'>
<p>Qty of Books:
<input type="text" name="bkqty" id='bk'>
</p>
<p>Qty of Software:
<input type="text" name="software" id='softw'>
</p>
<p>Total:
<input type='text' id='total'>
</p>
<p>
<input type='submit' value='send' id='submit'>
</p>
</form>
</div>

In my javascript function I am trying to get the values from a form user input to a function I created and the output the answer

I am trying to get the values from my form into a function and return a value
Here is my function
function createInput(){
var weight;
weight = document.bmiCalc.weight.value;
var height = getElementById('height').value;
input.onclick = function calcBMI()
{
// calculate users BMI
var BMI = weight * 703 / Math.pow(height, 2);
return BMI;
}
document.getElementById("BMI").appendChild();
}
and here is my form code from my html page
<form id="bmiCalc">
<h2> Calculate your Current BMI</h2>
<p><label> Please enter your weight in lbs: <input type="text" name = "weight" id= "weight"></label></p>
<p><label> Please enter your height in inches: <input type="text" name ="height" id="height"></label>
<button type="submit">Submit</button></p>
<p><label> Your current BMI is: <input name="BMI" id="BMI"></label></p>
</form>
Changed your html and js:
http://jsfiddle.net/CQxnx/
html:
<h2> Calculate your Current BMI</h2>
<label> Please enter your weight in lbs:</label> <input type="text" name="weight" id="weight">
<br />
<label> Please enter your height in inches:</label> <input type="text" name="height" id="height">
<br />
<input type="button" value="calculate" onclick="calcBMI();" />
<br />
<div id="msg"></div>
js:
function calcBMI(){
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
// calculate users BMI
var BMI = weight * 703 / Math.pow(height, 2);
var msg = document.getElementById('msg');
msg.innerHTML = 'Your current BMI is:' + BMI;
}
You seem to be a bit off, but you never actually call the createInput function. Even after that, you don't actually append the input button. There is no BMI ID element, and createInput would calculate the weight/height as they are when it's called, not when the button is clicked.
Instead, you should just put the button in the DOM to begin with and bind the calculation function to it.
document.getElementById('calculate').addEventListener('click', function () {
document.getElementById("BMI").textContent =
document.getElementById('weight').value * 703 /
Math.pow(document.getElementById('height').value, 2);
});
http://jsfiddle.net/fsKNb/

Categories