Plus operator in JavaScript doesn't sum my values - javascript

I'm trying to calculate the number of payments but output was wrong so i tried to calculate a simple operation on the month value.But "+" operator doesn't sum my values it acts like string.For example 3 and 5,output isnt 8 its 35.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mortgage Calculator</title>
<script>
function validateForm() {
var principal = princ.value;
var interestrate = interest.value;
var monthlypayment = monthly.value;
var months=(principal)+(interestrate);
document.getElementById("demo").innerHTML=months;
}
</script>
</head>
<body>
<p id="demo"></p>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Principal: <input type="text" id="princ" name="principal">
<br>
<br> Interest Rate: <input type="text" id="interest" name="interestrate">
<br/>
<br/> Monthly Payment: <input type="text" id="monthly" name="monthlypayment">
</form>
<button onclick="validateForm()">Run</button>
</body>
</html>

The values you are summing are strings. You need to convert them to integers:
parseInt(principal)+parseInt(interestate)
The reason for this is that input values are always strings. AFAIK, this is even if you set the type to number. parseInt(s) converts a string s to an int.

The actual type of the value is string. That's why string concatenation is happening. You have to use parseInt to convert string to integer to perform intended arithmetic operation.
Change:
var months=(principal)+(interestrate);
To:
var months = parseInt(principal) + parseInt(interestrate);

var months=parseInt(principal)+parseInt(interestrate);
Values need to be converted to an integer first.

Your input values are treated as string as they are textbox inputs. Parse the values first before adding them up.
e.g.
var principal = parseInt(princ.value);
var interestrate = parseInt(interest.value);

Related

Input tag not giving correct output

What I want is, on button click the sum of value in two input texts should be consoled, but for Any value for two input texts that I give, it always gives 0,0 as output, what am I doing wrong? And since both of them are 0, their sum is also becoming 0.
HTML
<!DOCTYPE html>
<html>
<head>
<title>WeB </title>
</head>
<body>
<input type="number" id = "num1" >
<input type="number" id = "num2" >
<button id = "add">+</button>
<script src = "app.js"></script>
</body>
</html>
JS
let num1 = Number(document.getElementById('num1').value)
let num2 = Number(document.getElementById('num2').value)
document.getElementById("add").addEventListener("click",function(){
console.log(num1,num2);
console.log(num1+num2);
})
You need to get the latest value of the input on click of the button
document.getElementById("add").addEventListener("click", function() {
let num1 = Number(document.getElementById('num1').value)
let num2 = Number(document.getElementById('num2').value)
console.log(num1, num2);
console.log(num1 + num2);
})
<input type="number" id="num1">
<input type="number" id="num2">
<button id="add">+</button>
This is the order of events:
You read the values of the inputs (empty strings) and convert them to numbers (0) then store them in variables
You bind an event listener to add those numbers together when something is clicked
You type something into the inputs
You click the button which
Logs the values of the variables
adds the values of the variables together
The variables still contain the values from the time you read the inputs
You need to move step 1 so it goes inside step 4 (i.e. inside the function you use as the event listener)

Javascript: Average of 2 user input values

I apologize for the basic question but I have been trying to make this work for a long time and I just can't seem to get this code to return a value.
I am embarrassed to admit how long I have been attempting to make it work, and how many StackOverflow questions that were related that I have looked at, however, none were as simple as my code, and when I attempted to make something closer to how mine looked, it just wouldn't alert anything.
The idea is the following:
User inputs 2 numbers,
clicks the button,
and is alerted the average of the numbers they input.
My alert has been NaN no matter how many iterations I have made. I could really use some advice. Thanks in advance!
<html>
<head>
<title> Javascript </title>
<body>
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input></p>
<p> Number 2<input type="text" id="userInput2"></input></p>
<button id="averageButton"> Calculate</button>
<script type="text/javascript">
function average(a, b) {
return ((a + b) /2);
}
document.getElementById("averageButton").onclick = function (){
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
alert(average());
}
</script>
</body>
</html>
You failed to pass the numbers a,b to your function - a simple mistake.
But since the inputs are seen as strings you also need to convert them to numbers a*1
See commented code
<html>
<head>
<title> Javascript </title>
<body>
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input></p>
<p> Number 2<input type="text" id="userInput2"></input></p>
<button id="averageButton"> Calculate</button>
<script type="text/javascript">
function average(a, b) {
// force the input as numbers *1
return ((a*1 + b*1) /2);
}
document.getElementById("averageButton").onclick = function (){
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
// pass the numbers to the average function!
alert(average(a,b));
}
</script>
</body>
</html>
At first glance you might need to convert your input values from strings to floats and actually pass them to the average function.
You may want to change the inputs to
<input type="number"> to prevent users from adding non-numeric values.
Secondly parse your inputs as document....value returns string,
var a = parseFloat(document.getElementById("userInput1").value);
var b = parseFloat(document.getElementById("userInput2").value);
If you do just this you wouldn't have to deal into the funny business of doing a*1.
// force the input as numbers *1
return ((a*1 + b*1) /2);
This block isn't required since multiplying a string with a number returns a NaN value.
function average(a, b) {
return ((a + b) / 2);
}
document.getElementById("averageButton").onclick = function() {
var a = document.getElementById("userInput1").value;
var b = document.getElementById("userInput2").value;
alert(average());
}
<p> Enter two number for an average below </p>
<p> Number 1<input type="text" id="userInput1"></input>
</p>
<p> Number 2<input type="text" id="userInput2"></input>
</p>
<button id="averageButton"> Calculate</button>

Try/Catch Statement for NaN values in JavaScript

I'm working on this calculator for JavaScript where a ice hockey goalie will be able to enter information to calculate his goals against average, or his GAA. I've got the calculator working (although I wish I could format the output to #.##, but oh well), but I want to be able to handle exceptions arising from say, a user entering a letter instead of a number, which would result in a NaN output via a try/catch statement, except I'm not sure how you would format it to look for NaN values. Any idea how I might go about doing that? Here is my code:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<Title>Goals Against Average Calculator</Title>
<body>
<script src="modernizr.custom.05819.js"></script><!--Links to file containing modernizer library-->
<!-- Navigation -->
<nav>
<ul class="w3-navbar w3-black">
<li>Home</li> <!--Link to Home Page-->
<li>NHL Teams</li><!--Link to Page of NHL Teams-->
<li>AHL Teams</li><!--Link to Page of AHL Teams-->
<li>WHL Teams</li><!--Link to Page of WHL Teams-->
<li>G.A.A. Calculator</li><!--Link to GAA Calculator-->
<li>Fan Survey</li><!--Link to Fan Survey Page-->
</ul>
</nav>
<header>
<h1 style="text-align:center;">Goals Against Average Calculator</h1><!--Title of Page-->
</header>
<article>
<form>
<fieldset>
<label for="GoalsAllowed">
Enter Number of Goals Allowed
</label>
<input type="Goals" id="GoalsAllowed" /><!--Input for Goals Allowed-->
</fieldset>
<fieldset>
<label for="MinutesPlayed">
Enter Minutes Played
</label>
<input type="MinPlayed" id="MPlayed" /><!--Input for Minutes Played-->
</fieldset>
<fieldset>
<label for="GameLength">
Regulation Game Length
</label>
<input type="Minutes" id="MinGame" /><!--Input for Length of Regulation Game-->
</fieldset>
<fieldset>
<button type="button" id="button">Calculate</button><!--Calculation Button-->
</fieldset>
<fieldset>
<p id="GAA"> </p>
</fieldset>
</form>
</article>
<script>
function convert()
{
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MPlayed").value;
var GameLength = document.getElementById("MinGame").value;
var GAA = (Goals * GameLength) / Minutes;
//window.alert("Swords and Sandals: " + GAA);
document.getElementById("GAA").innerHTML = "Your Goals Against Average is: " + GAA;
}
document.getElementById("button").
addEventListener("click", convert, false);
</script>
</body>
</html>
EDIT: The comment about decimal formatting isn't why I'm posting. It was merely for cosmetic reasons on my part on what I would like it to look like, but it works fine as it is.
Others have provided answers about Number.isNaN, so I won't go into details on that; it's the right answer. :-)
As for your secondary question, how to format the number to two decimal places, all numbers have a function toFixed(numberOfPlaces) that returns a formatted string. Now, this function does not perform any rounding; it just chops off the remaining decimals. So for instance:
var num = 1.005;
var formatted = num.toFixed(2);
..will return "1.00". You probably want to round the input so that it gets handled and formatted consistently. To do that, there is a function Math.round() that you can call. It always rounds the number to have no decimals at all. You want two decimals, so that's a non-starter, right? Well, here's a little trick: If you multiply the number by 100 first, then you bump those two digits you want to keep to the left of the decimal. After rounding it, divide it by 100 to put them back in the right place.
Putting it all together:
var input = Number(prompt("Give me a number"));
if (Number.isNaN(input))
alert("That isn't a valid number!");
else
{
input = Math.round(input * 100) / 100;
var formatted = input.toFixed(2);
alert("Your input was: " + formatted);
}
You can also restrict the user to enter only number by using the type="number" to the input type in the HTML directly. HTML 5 introduces the number` type.
<input type="number" id="GoalsAllowed" /><!--Input for Goals Allowed-->
My experience is that the best way to check for NaN is a little verbose, but as far as I've seen it's bulletproof.
var numStr = prompt('Give me a number');
var num = Number.isNaN(Number(numStr));
If numStr was a valid number string, num will be false; if it was not, num will be true.
Why not just use Number.isNaN without converting to a number first? Well, Number.isNaN doesn't check whether a value is a Number or not, it literally just checks if it's NaN, so Number.isNaN('totally not a number') will return false.
Here is a JS Fiddle showing you what you can do: https://jsfiddle.net/iamjpg/huk8yp0L/
var convert = function() {
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MPlayed").value;
var GameLength = document.getElementById("MinGame").value;
var regex = /^[+-]?\d+(\.\d+)?$/
if (!regex.test(Goals) || !regex.test(Minutes) || !regex.test(GameLength)) {
alert('Please only enter numeric values.');
return false;
}
var GAA = (Goals * GameLength) / Minutes;
//window.alert("Swords and Sandals: " + GAA);
document.getElementById("GAA").innerHTML = "Your Goals Against Average is: " + Math.ceil(GAA * 100) / 100;
}
document.getElementById("button").addEventListener("click", convert, false);
var regex = /^[+-]?\d+(\.\d+)?$/ - Checks if you are entering a number or float.
Math.ceil(GAA * 100) / 100; - Rounds your calculated value to the nearest hundredth.
Hope this is helpful.
You have to convert each value to number
goal = +goal
and check if it is a number
if(isNaN(goal)){
// show error
}else{
// show result
}

I have issues with my JavaScript

I don't what happen with my script can i please point out where is my mistake. 1 to 9 all condition working fine but when you put 10-12 is not work
<form method="post" enctype="multipart/form-data" action="#">
<input type="hidden" value="2" id="itemstock" name="itemstock">
<input value="1" name="quantity" id="quantity" class="text">
<button type="submit" onClick="return checkoption();" >Click </button>
</form>
Javascript
function checkoption()
{
var itemqty = document.getElementById('quantity');
var iss = document.getElementById('itemstock');
if(itemqty.value > iss.value)
{
alert('We have Currently '+iss.value+' In Stock');
}
else
{
alert('add to cart');
}
}
Thank you in advance
Screen short see qty i put 13 but its not showing error
Using the < or > operators with strings will compare the values alphabetically, which is probably not what you want.
You need to compare these as numbers, not as strings. JavaScript allows you to easily cast a string to a number using +, like so:
var qty = +itemqty.value;
var isv = +iss.value;
if(qty > isv)
{
// ...
}
However, you can also use parseInt (which will return NaN if the value is invalid) if you want to add more error checking in your code.
The .value attribute on a text field such as input is a string, not a number. Therefore, you compare strings lexicographically. Change them into numbers, either via parseInt(str, 10) or via +str.

Strip data to number and decimal then jquery set input value to variable

I'm taking data from an encrypted php script which outputs variables as e.g. %%Price%%
Annoyingly those variables are not just a decimal and numeric value.
The encrypted script renders %%Price%% as:
<font color="green"><strong>Sale Price: $2,489.99</strong></font>
I want to strip the value of %%Price%% to price (number and decimal) and then place that result in a hidden form field as the value.
I have tried:
<form id="add-to-cart">
<input type="hidden" name="price" id="price" value=""/>
<button type="submit"> Review & Order</button>
</form>
<script>
var price = "%%Price%%";
var newPrice = price.replace(/[^0-9\.]/g, '');
jQuery("#price").val(newPrice);
</script>
...but this gives an empty result
I would use:
newPrice = parseFloat(price.substring(2, price.length - 3));
I checked your code with a jsfiddle and it seems ok. Check here: http://jsfiddle.net/CmHn6/1/. I actually replaced:
var price = "%%Price%%";
with:
var price = '<font color="green"><strong>Sale Price: $2,489.99</strong></font>';
as you said in your example. Notice that I used single quotes there. If your encrypted script does not take this into account, your line could end up like:
var price = "<font color="green"><strong>Sale Price: $2,489.99</strong></font>";
which would result in a syntax error and would not fill in your input element.
If your string never use single quotes, then you can use single quotes in your code, like in my example.
If not, you could put %%Price%% inside a hidden div, and read this value from there:
<div id="pricediv" display="style: none">%%Price%%</div>
<form id="add-to-cart">
<input type="hidden" name="price" id="price" value=""/>
<button type="submit"> Review & Order</button>
</form>
<script>
var price = $("#pricediv").html();
var newPrice = price.replace(/[^0-9\.]/g, '');
jQuery("#price").val(newPrice);
</script>

Categories

Resources