My condition if is not executed. Why, please? - javascript

In this function, the program does not want to execute my condition if. I stupidly tried to reverse the "if" in "else if", and "else if" to "if" but, of course, that doesn't change anything.
I want when the input value is <12000, the textual content of "amount6" to be changed to "unqualified!
HTML:
<p>CALCUL GAINS PILOTE QUALIFIE</p>
<p class="minimum2">(Points total minimum groupe conseillers + groupe
animateurs = 12000 )</p>
<div class="blocklabel5">
<label for="points amount" class="label6">Entrez points groupe
conseillers</label>
<input type="number" class="amountEnter6" id="amount6">
</div>
<div class="blocklabel6">
<label for="points amount" class="label7">Entrez points groupe
animateurs</label>
<input type="number" class="amountEnter7" id="amount7">
<input type="submit" value="Commissions pilote qualifié" id="submit7"
class="submitEnter7" onclick="calcAmount6()">
</div>
<p id="marginAmount6" class="enterMargin6">0€</p>
</div>
</div>
JAVASCRIPT (calcAmount6)
function calcAmount6(){
var userAmount5 = document.getElementById("amount6").value;
var userAmount6 = document.getElementById("amount7").value;
var oneLevel1 = 12000;
if (userAmount5 + userAmount6 < oneLevel1) {
document.getElementById("marginAmount6").textContent = "Non-qualifié!";}
else if (userAmount5 + userAmount6 >= oneLevel1) {
document.getElementById("marginAmount6").textContent =
Math.round(userAmount5 * 13 / 100) + (userAmount6 * 5 / 100) + "€";}
}

You must convert your strings to numbers
var userAmount5 = Number(document.getElementById("amount6").value);
var userAmount6 = Number(document.getElementById("amount7").value);
Assuming your input is something like
var userAmount5 = document.getElementById("amount6").value; // 10
var userAmount6 = document.getElementById("amount7").value; // 20
then you get this result
userAmount5 + userAmount6 === '1020' // equals true
and not 30 as you may expect.
but if you convert your strings to numbers first you get the desired result
Number(userAmount5) + Number(userAmount6) === 30 // equals true

document.getElementById("id").value would return the value as a string, so you might need to cast it to a number: Number(document.getElementById("id").value)

Try with:
var userAmount5 = parseInt(document.getElementById("amount6").value);
var userAmount6 = parseInt(document.getElementById("amount7").value);

Related

Javascript and JQuery issue with Wordpress

I'm working on a website and wanting to do advanced stuff (at least for me) that is way over my head. My javascript knowledge is extremely limited and need help with this.
I have an html form that accepts 5 text input fields labeled 1-5 representing a percentage distribution. I want to use javascript to do the following:
Read all fields and make sure the total sum is equal to 100.
Disable unnecessary fields when total sum equals 100.
Disable Submit button if total sum is not 100%.
Add the % at the end of the user entry.
I found two separate scripts to accomplish all this, one is javascript and the other one is JQuery. For some reason the JQuery is not working and it is yielding the following error:
Uncaught TypeError: $ is not a function
I've tried modifying the JQuery code, as suggested in multiple solutions online, like the following:
(function($){ "JQuery Code here" })(jQuery);
This get's rid of the error, however the JQuery code does not work.
Both the javascript.js and the JQuery.js files are being propperly enqueued in the WP theme's functions.php file.
Any help will be greately appreciated!!
HTML
<label for="entryFee">Entry Fee:</label>
<input id="entryFee" name="entry_fee" onblur="this.value = '$' + formatNumber(this.value, 1, 2, true)" type="text" value="" placeholder="$100.00" />
<h4>Prize Distribution</h4>
<label for="1stPlace">1st Place:</label> <input id="1stPlace" name="1st_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="60%" maxlength="3" size="4" class="percentageField" required />
<label for="2ndPlace">2nd Place:</label> <input id="2ndPlace" name="2nd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="30%" maxlength="3" size="4" class="percentageField" />
<label for="3rdPlace">3rd Place:</label> <input id="3rdPlace" name="3rd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="10%" maxlength="3" size="4" class="percentageField" />
<label for="4thPlace">4th Place:</label> <input id="4thPlace" name="4th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />
<label for="5thPlace">5th Place:</label> <input id="5thPlace" name="5th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />
<span id="percent">0</span>%
<input id="submitButton" type="submit" value="Submit" disabled>
</form>
Javascript
// Reformats a number by inserting commas and padding out the number of digits
// and decimal places.
//
// Parameters:
// number: The number to format. All non-numeric characters are
// stripped out first.
// digits: The minimum number of digits to the left of the decimal
// point. The extra places are padded with zeros.
// decimalPlaces: The number of places after the decimal point, or zero to
// omit the decimal point.
// withCommas: True to insert commas every 3 places, false to omit them.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
JQuery
(function($){
$('.percentageField').keyup( function () {
//limit the value to between 0 and 100
var thisVal = parseInt($(this).val(), 10);
if (!isNaN(thisVal)) {
thisVal = Math.max(0, Math.min(100, thisVal));
$(this).val(thisVal);
}
//get total of values
var total = 0;
$('.percentageField').each(function() {
var thisVal = parseInt($(this).val(), 10);
if (!isNaN(thisVal))
total += thisVal;
});
//change the value of the current entry to limit sum to 100
if (total > 100) {
$(this).val(thisVal - (total - 100));
total = 100;
}
if (total == 100) {
//enable submit button
$('#submit_button').removeAttr('disabled');
//disable empty input fields
$('.percentageField').each(function() {
var thisVal = parseInt($(this).val(), 10);
if (isNaN(parseInt($(this).val(), 10)) || thisVal == 0)
$(this).attr('disabled','disabled');
});
}
else {
//disable submit button
$('#submitButton').attr('disabled','disabled');
//enable all input fields
$('.percentageField').removeAttr('disabled');
}
//update percentage
$('#percent').html(total);
});
})(jQuery);
The JQuery script was running before the DOM was ready.
Enclosing the entire code set within $('document').ready(function() did the trick:
(function($){
$('document').ready(function()
{ <<JQuery Code>> });
})(jQuery);

Javascript percentage calculator adder function not working [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I'm building a percentage calculator to learn JavaScript. Below is my attempt.
One of the functions works just fine (the one that takes the percentage away from the number), but the one that adds the percentage to the number seems to be adding the values like they are a string. I've had a look for solutions and using parseInt() seems to crop up quite a bit but I can't seem to implement it with my present code so I'm hoping someone can help.
function myFunction() {
var per = document.getElementById("input1").value;
var num = document.getElementById("input2").value;
var sum = num / 100 * per;
var output = num - sum;
console.log(output);
document.getElementById("demo").innerHTML = output;
}
function myFunction2() {
var per = document.getElementById("input3").value;
var num = document.getElementById("input4").value;
var sum = num / 100 * per;
var output = sum + num;
console.log(output);
document.getElementById("demo1").innerHTML = output;
}
<section id="number less percentage"></section>
<h1>Number less percentage</h1>
<input id="input2" placeholder="enter the number"></input>
<input id="input1" placeholder="enter percentage of a number"></input>
<button value='send' id="submit" onclick="myFunction()">Click for
result</button>
<p id="demo"></p>
</section>
<section id="number plus percentage"></section>
<h1>Number plus percentage</h1>
<input id="input4" placeholder="enter the number"></input>
<input id="input3" placeholder="enter percentage of a number"></input>
<button value='send' id="submit" onclick="myFunction2()">Click for
result</button>
<p id="demo1"></p>
</section>
JavaScript is a bit funny when it comes to numbers and addition. For example:
'20' - '30' === 10 // `-` always coerces operands to numbers
'20' + '30' === '2030' // `+` with strings is interpreted as concatenation
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to numbers before proceeding with the addition or subtraction. Your code can be:
function calculate() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}

Getting NaN instead of a number when calculating a value from a text input even after using the parseInt() method

HTML
I'm first converting the weight (in lbs) to kilograms multiplying it times kgVal to then divide this weight by the value of heightInMts as follows ((kgs / heightInMts) / heightInMts). Instructions
1. divide your weight in kilograms (kg) by your height in metres (m)
2. then divide the answer by your height again to get your BMI.
<h1>BMI calculator</h1>
<div class="contact-clean">
<form method="post" id="formOne">
<div>
<p>Feet</p>
<input type="number" id="feetInput" class="form-control col-2"/>
</div>
<div>
<p>Inches</p>
<input type="number" id="inchesInput" class="form-control col-2"/>
</div>
<div>
<p>Weight in pounds</p>
<input type="number" id="weightInput" class="form-control col-2"/>
</div>
<button id="calculate" class="btn btn-primary" type="button">Calculate</button>
</form>
<p id="result"></p>
Calculate again!
</div>
JS
var lbs = document.getElementById('weightInput');
var feetInput = document.getElementById('feetInput');
var inchesInput = document.getElementById('inchesInput');
var bmi;
var weight;
var kgVal;
var feet = parseInt(feetInput.value);
var inches = parseInt(inchesInput.value);
var resultOutput = document.getElementById('result');
var calculate = document.getElementById('calculate');
var heightInMts = parseInt(feet / 3.281);
resultOutput.setAttribute('style','display:none');
var form = document.getElementById('formOne');
var recalculateLink = document.querySelector('a.hidden');
calculate.addEventListener('click', compute);
function compute(){
feet = parseInt(feetInput.value);
inches = parseInt(inchesInput.value);
weight = parseInt(lbs.value);
kgVal = 0.453592;
var kgs = weight * kgVal;
var totalInches = feet * 12 + inches;
bmi = (kgs / heightInMts / heightInMts);
// Hide the form
form.setAttribute('style','display: none');
resultOutput.innerHTML = 'Your BMI is ' + bmi;
resultOutput.setAttribute('style', 'display: block');
recalculateLink.setAttribute('style', 'display: block');
}
// Reopen the form and clear all fields
recalculateLink.addEventListener('click', function () {
form.setAttribute('style','display: block');
recalculateLink.setAttribute('style', 'display: none');
feetInput.value = '';
inchesInput.value = '';
lbs.value = '';
resultOutput.innerHTML = '';
});
The value I get is NaN. Can someone tell me what I'm doing wrong in
the calculation. Thanks.
NaN in javascript comes when you try to do a mathematical operation on two operands that are not numbers and can't be converted to a number
E.G.
1 - "a" = NaN
1 * "a" = NaN
1 / "a" = NaN
Since in these cases, JS can't convert string "a" to a number and gives NaN.
For more info on NaN, check MDN docs at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
Use a wrapper
let x = function( i) {
let r = parseInt( i);
if ( isNaN( r)) {
return 0;
}
return r;
}
x('fart'); // result 0

javascript alert somehting I am having trouble with [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html

How to add two strings as if they were numbers? [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html

Categories

Resources