Issue with simple calculation script - javascript

I'm trying to make a really simple calculator for my website.
Basically, I want people to be able to put in their weight into a text box, click "Calculate Dose" and then the script multiplies their weight by a number that I will set myself for each page.
Here is what I have right now. Not only does it not work, but it also stops one of my ads from displaying:
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()">
<input id="result" />
</div>
<script>
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight.value * 1;
result.value = dosage;
}
</script>
What's wrong with it?

You are missing closing tag /> in your button
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You already stored weight value
var weight = document.getElementById('inputweight').value;
So you dont need this var dosage = weight.value * 1;
So use var dosage = weight * 1;
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}

this line:
var weight = document.getElementById('inputweight').value;
and this:
var dosage = weight.value * 1;
do not work together well. You are retrieving the value, then the value of that... which cannot work.
So, replace the second line with:
var dosage = weight * 1;
Besides: You should check the console for errors, it should show up there.
I assume (or, guess, more correctly) that the ad that is no longer working stops because the javascript execution is typically terminated after an error.

Just update this line (remove the value attribute which is already extracted above):
var dosage = * 1;
This will work but you might also want to add this for increased type safety (it parses weight as a number):
var dosage = parseInt(weight, 10) * 1;

In your code block you are missing a closing / at the end of the second input statement. Which should be giving you an issue in your html.
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You also don't need weight.value again in the third line of your function. Instead it should be:
var dosage = weight * 1;

Fiddle demonstrating your example modified to work:
http://jsfiddle.net/x38ommxs/
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()" />
<input id="result" />
</div>
Added missing closing tag on button
Changed dosage to multiply the value stored in weight by one.

Related

Is there a way to multiply inputs when they begin with a decimal like this- .125 or even 0.7854... My result winds up being 0 or NaN

I need some insight again. I am trying to multiply three inputs times two hidden numbers. Two inputs being the same number (since i have yet to figure out how to Square a input). The calculation i am after is a Force calc we use in O&G. Wire diameter * Wire Diameter * Well Head Pressure * .7854(variable) * 1.5;; Eg. .125 * .125 * 6500 * .7854 * 1.5; Which should result in 119.65 (lbs)- instead i get NAN or if i use decimal like this 0.125 i get a result of 0. To Note the function works if i leave the decimal out all together but the answer is wrong naturally.
My Code
<div class="containerForce">
<p>
<h1>Force Calculation - Weight Required to Fall</h1>
<label>Wire OD</label>
<input type="number" id="num05">
<label>Wire OD</label>
<input type="number" id="num06">
<label>Well Head Pressure</label>
<input type="number" id="num07">
<p>
<input type="button" id="btn01" style="background-color: rgb(104, 199, 206)"
value="Required Weight" onclick="cal()" />
</p>
<p id="total3"></p>
</div>
Java Function
function cal() {
var numZero5 = document.getElementById('num05').value;
var numZero6 = document.getElementById('num06').value;
var numZero7 = document.getElementById('num07').value;
var total3 = parseInt(numZero5) * parseInt(numZero6) * parseInt(numZero7) * .7854 * 1.5;
var p = document.getElementById('total3');
p.innerHTML += total3;
}
Currently you are parsing your inputs to Integers. Integers are whole numbers, so everything after the decimal seperator is thrown away.
You can reproduce this behaviour by executing parseInt(1.5) in the browser console.
The method you are looking for is parseFloat() or Number(). I personally would go with parseFloat().
Additionally, you might want to change your last line to p.innerHTML = total3; so you replace the result in the paragraph instead of concetinating your results.
<div class="containerForce">
<h1>Force Calculation - Weight Required to Fall</h1>
<label>Wire OD</label>
<input type="number" id="num05">
<label>Wire OD</label>
<input type="number" id="num06">
<label>Well Head Pressure</label>
<input type="number" id="num07">
<p>
<input type="button" id="btn01" style="background-color: rgb(104, 199, 206)"
value="Required Weight" onclick="cal()" />
</p>
<p id="total3"></p>
</div>
<script>
function cal() {
var numZero5 = document.getElementById('num05').value;
var numZero6 = document.getElementById('num06').value;
var numZero7 = document.getElementById('num07').value;
var total3 = parseFloat(numZero5) * parseFloat(numZero6) * parseFloat(numZero7) * .7854 * 1.5;
var p = document.getElementById('total3');
p.innerHTML = total3;
}
</script>

get the quotient of two textbox which has an onChange event

I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.
function sum(){
var ua = document.getElementById('ua').value;
var ub = document.getElementById('ub').value;
var result = parseInt(ua) + parseInt(ub);
if (!isNaN(result)) {
document.getElementById('tu').value = result;
document.getElementById('tu').dispatchEvent(new Event('change'));
}
}
function suma(){
var ua = document.getElementById('ua').value;
var ga = document.getElementById('ga').value;
var result = parseInt(ua) * parseInt(ga);
if (!isNaN(result)) {
document.getElementById('uu').value = result;
document.getElementById('uu').dispatchEvent(new Event('change'));
}
}
function sumb(){
var ub = document.getElementById('ub').value;
var gb = document.getElementById('gb').value;
var result = parseInt(ub) * parseInt(gb);
if (!isNaN(result)) {
document.getElementById('a').value = result;
document.getElementById('a').dispatchEvent(new Event('change'));
}
}
function s(){
var uu = document.getElementById('uu').value;
var a = document.getElementById('a').value;
var result = parseInt(uu) + parseInt(a);
if (!isNaN(result)) {
document.getElementById('tt').value = result;
document.getElementById('tt').dispatchEvent(new Event('change'));
}
}
function g(){
var tt = document.getElementById('tt').value;
var tu = document.getElementById('tu').value;
var result = parseFloat(tt) / parseFloat(tu);
if (!isNaN(result)) {
document.getElementById('gpa').value = result;
}
}
<input type="text" id="ua" name="ua" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="suma();">
<input type="text" id="uu" name="uu" size="7" onchange="s();"/>
<input type="text" id="ub" name="ub" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="sumb();">
<input type="text" id="a" name="a" size="7" onchange="s();"/>
<input type="text" id="tu" name="tu" onchange="g();"/>
<input type="text" id="tt" name="tt" onchange="g();"/>
<label>GPA</label>
<input type="text" id="gpa" />
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).
That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.
As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?
In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:
var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');
function updateQuotient () {
var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
if (!isNaN(result)) {
resultElement.value = result;
}
}
dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);
<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">

Simple time and half calculator in JavaScript

I have made a simple time and half calculator in HTML and JavaScript, but for some reason, when I click the Calculate button, the P element does not show the result.
Here is my code:
http://codepen.io/chrissylvester10/pen/wJxder
html>
<head>
</head>
<body>
<h1>Time and Half Calculator</h1>
<input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
<input type="button" value="Calculate" onclick="calculator()">
<p id="result"></p>
</body>
</html>
var fare = document.getElementById("#fare").value;
function calculator() {
var result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
Please fork it because I need to see the changes.
First thing, you don't need the # in var fare = document.getElementById("#fare").value;.
It should be var fare = document.getElementById("fare").value;
That line of code should also be inside the function, so it will read the new value every time you change it, otherwise, it will just return 0.
Lastly, you want to parse the number so it isn't misread as a string.
function calculator() {
var fare = parseInt(document.getElementById("fare").value);
var result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
edit:
A much simpler way to do this would be
function calculator() {
document.getElementById("result").innerHTML = document.getElementById("fare").value*1.5;
}
You are getting the value at the start and not the actual value.
Solution: Move the fare declaration inside of the function.
Small change: Get only fare as id.
function calculator() {
var fare = +document.getElementById("fare").value,
result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
<h1>Time and Half Calculator</h1>
<input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
<input type="button" value="Calculate" onclick="calculator()">
<p id="result"></p>
What about to enclose your Javascript into <script> tags?
And remove # from fare.

Questions about javascript variable, need help~

I put 5、4 into the blanks 1st Number、2nd Number, and clicked Multiply in the output. I am looking forward to get 20, but I got zero, why?
Here's the code (also on JSBin):
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
function multiplyBy() {
var c = num1 * num2;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
var c = num1 / num2;
document.getElementById("result").innerHTML = c;
};
body {
margin: 30px;
}
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<button onClick=d ivideBy()>Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
If you are using button & form you need to specify the type of button that is submit,button or reset. The default is submit which will submit the form.
Secondly there is a typo in
<button onClick=d ivideBy()>Divide</button>
instead it will be onclick = "devideBy()"
You need to use these two variable inside the function.Reason being when js is parsing at beginning it is setting the value to 0 as those inputs are empty & inside the function you are getting 0.
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
HTML
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<!--button type button -->
<button type = "button" onClick="divideBy()">Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
JS
function multiplyBy() {
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var c = num1 * num2;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var c = num1 / num2;
document.getElementById("result").innerHTML = c;
};
Working jsfiddle
Your first two lines run immediately when the page loads, not later when you click one of the buttons. So you get the values of the inputs as of when the page loads, which is "". * implicitly converts its operands to numbers, so "" becomes 0, and 0 * 0 is 0.
You want to get the .value from the input elements inside your click handlers, so you get the current value:
// Here we get the elements, but not their values
var num1input = document.getElementById("firstNumber");
var num2input = document.getElementById("secondNumber");
function multiplyBy() {
// Get the values as they are *now*
var c = num1input.value * num2input.value;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
// Get the values as they are *now*
var c = num1input.value * num2input.value;
document.getElementById("result").innerHTML = c;
};
body {
margin: 30px;
}
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<button onClick=d ivideBy()>Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
Side note: The value of an input is always a string. It happens that / and * will both implicitly coerce their operands to numbers, but if you did the same thing with + you'd get concatenation (one string appended to the end of the other), not addition. You want to convert your values to numbers. This answer discusses the various ways you can convert numeric strings to numbers in JavaScript.
Side note 2: As user2181397 pointed out, while the above will make your Multiply button work, there are two additional issues with your Divide button:
The default type of a button element is "submit", which will submit the form instead of just calling the click handler. Give type="button" (like you did on the input).
onClick=d ivideBy() should be onclick="divideBy()"

Why won't my JS function work properly?

I am very new to Javascript, so please pardon my lack of knowledge.
I am trying to use Javascript to find the slope of two data points (x1,y1)(x2,y2). The equation for the slope is m=y1-y2/x2-x1. Here is what I have done so far in JS fiddle: http://jsfiddle.net/1wvfz0ku/
The problem is that when I try to calculate the points only NaN appears.
Like I said I am very new at coding in JS, so I can't see where I have messed up in. Any help would be much appreciated! :-)
<!DOCTYPE html>
<html>
<body>
<div style="width:250px;height:auto;margin:auto;">
<h1>Find the Slope of Two Data Points</h1>
<p>
Find the slope of two sets of points:
</p>
<var>M</var>=<p id="slope"></p>
Enter your points below:
<form id="points">
X<sub>1</sub>: <input type="text" id="x1"/><br/>
X<sub>2</sub>: <input type="text" id="x2"/><br/>
Y<sub>1</sub>: <input type="text" id="y1"/><br/>
Y<sub>2</sub>: <input type="text" id="y2"/><br/>
</form>
<script>
function findSlope() {
//The points//
var xOne = document.getElementById("x1").value;
var xTwo = document.getElementById("x2").value;
var yOne = document.getElementById("y1").value;
var yTwo = document.getElementById("y2").value;
//slope equation//
var op1 = yTwo - yOne;
var op2 = xTwo - xOne;
var answer = op1 / op2;
document.getElementById("slope").innerHTML = answer;
}
function reset(){
document.getElementById("points","slope").reset();
}
</script>
<button type="submit" onClick="findSlope()">Find the Slope</button>
<button type="submit" onClick="reset()">Clear Points</button>
</div>
</body>
</html>
This works just fine unless xTwo - xTwo is 0, in which case you're trying to divide a number by 0, which is defined in JavaScript to be NaN.
That said: The value property of elements is always a string. It just happens that all of the operations you've used (-, /) will implicitly convert from string to number, but if you'd used + you'd've gotten some very odd results indeed (because + with strings is concatenation, not addition). Better to explicitly ensure you're dealing with numbers, by using parseInt(theString, 10) (if you're dealing with decimal).
Example allowing for xTwo - xOne being 0 and parsing the inputs as decimal:
function findSlope() {
//The points//
var xOne = parseInt(document.getElementById("x1").value, 10);
var xTwo = parseInt(document.getElementById("x2").value, 10);
var yOne = parseInt(document.getElementById("y1").value, 10);
var yTwo = parseInt(document.getElementById("y2").value, 10);
//slope equation//
var op1 = yTwo - yOne;
var op2 = xTwo - xOne;
var answer = op2 === 0 ? "flat or whatever" : op1 / op2;
document.getElementById("slope").innerHTML = answer;
}
function reset(){
document.getElementById("points","slope").reset();
}
<div style="width:250px;height:auto;margin:auto;">
<h1>Find the Slope of Two Data Points</h1>
<p>
Find the slope of two sets of points:
</p>
<var>M</var>=<p id="slope"></p>
Enter your points below:
<form id="points">
X<sub>1</sub>: <input type="text" id="x1"/><br/>
X<sub>2</sub>: <input type="text" id="x2"/><br/>
Y<sub>1</sub>: <input type="text" id="y1"/><br/>
Y<sub>2</sub>: <input type="text" id="y2"/><br/>
</form>
<button type="submit" onClick="findSlope()">Find the Slope</button>
<button type="submit" onClick="reset()">Clear Points</button>
http://www.w3schools.com/jsref/jsref_number.asp Use code x = Number(x) and do it for all variables

Categories

Resources