when i'm using the function to add two numbers together it appears next to each other like (2+2=22)
although it works well with other mathematical operators (* and /)
<html>
<head>
<title>Adding</title>
</head>
<body>
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
<script type="text/javascript">
function adding (a, b){
return (a + b);
}
document.getElementById("press").onclick = function(){
var first = document.getElementById("one").value;
var second = document.getElementById("two").value;
alert(adding(first, second));
}
</script>
</body>
You are adding the string "2" plus "2" hence they are just appended. You will need to typecast into a number first.
console.log(parseInt("2")+Number("2"))
The value attribute returns a string, for which the + operator is defined to concatenate. You can use the unary plus operator to simply convert them to a numbers.
function adding(a, b) {
return (a + b);
}
document.getElementById("press").onclick = function() {
var first = +document.getElementById("one").value;
var second = +document.getElementById("two").value;
alert(adding(first, second));
}
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
You can only write parseint where you return.
function adding (a, b){
return (parseInt(a) + parseInt(b));
}
document.getElementById("press").onclick = function(){
var first = document.getElementById("one").value;
var second = document.getElementById("two").value;
alert(adding(first, second));
}
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
Related
I am a beginner to JavaScript and am working on creating a simple calculator using functions. I am running into a problem where after entering two numbers and selecting the operation, I am receiving NaN as a result. However, if I run the functions in the console with numbers, it results correctly with a number instead of NaN. I'm returning my values and passing them into the calculation functions; what am I missing? I feel like it is a simple thing I am overlooking but cannot figure it out.
function getVals() {
var val1 = parseInt(document.getElementById('number1').value);
var val2 = parseInt(document.getElementById('number2').value);
return val1, val2;
}
function addNumber(val1, val2) {
var total = Number(val1) + Number(val2);
document.getElementById('result').innerHTML = (total);
return total;
}
function subtractNumber(val1, val2) {
var total = val1 - val2;
document.getElementById('result').innerHTML = (total);
return total;
}
function multiplyNumber(val1, val2) {
var total = val1 * val2;
document.getElementById('result').innerHTML = (total);
return total;
}
function divideNumber(val1, val2) {
var total = val1 / val2;
document.getElementById('result').innerHTML = (total);
return total;
}
function exponentiation(val1, val2) {
var total = val1 ** val2;
document.getElementById('result').innerHTML = (total);
return total;
}
<!doctype html>
<html>
<head>
<h1>Calculator</h1>
<body>
<input id="number1" placeholder="Enter text" onblur="getVals()">
<input id="number2" placeholder="Enter text" onblur="getVals()"><br>
<br>
<input type="submit" onclick="addNumber()" value="+">
<input type="submit" onclick="subtractNumber()" value="-">
<input type="submit" onclick="multiplyNumber()" value="x">
<input type="submit" onclick="divideNumber()" value="÷">
<input type="submit" onclick="exponentiation()" value="^"><br>
<br>
<b>Calculation:</b><br>
<p id="result"></p>
<script src="calculator.js"></script>
</body>
</html>
While you are getting the values of the input elements prior to doing the calculations. You are storing them in local variables that are not accessible outside of the getVals function and your various calculation functions are expecting the two values to be passed into them as arguments, but when you call them, you aren't passing anything.
One solution is to declare the input variables at a higher scope and just use them directly without any function arguments.
// By declaring the variables at a higher scope than any function that
// will use them, they beconme available to all of them.
let val1 = null;
let val2 = null;
function getVals() {
val1 = parseInt(document.getElementById('number1').value,10);
val2 = parseInt(document.getElementById('number2').value,10);
}
function addNumber() {
var total = Number(val1) + Number(val2);
document.getElementById('result').innerHTML = (total);
return total;
}
function subtractNumber() {
var total = val1 - val2;
document.getElementById('result').innerHTML = (total);
return total;
}
function multiplyNumber() {
var total = val1 * val2;
document.getElementById('result').innerHTML = (total);
return total;
}
function divideNumber() {
var total = val1 / val2;
document.getElementById('result').innerHTML = (total);
return total;
}
function exponentiation() {
var total = val1 ** val2;
document.getElementById('result').innerHTML = (total);
return total;
}
<!doctype html>
<html>
<head>
<h1>Calculator</h1>
<body>
<input id="number1" placeholder="Enter text" onblur="getVals()">
<input id="number2" placeholder="Enter text" onblur="getVals()"><br>
<br>
<input type="submit" onclick="addNumber()" value="+">
<input type="submit" onclick="subtractNumber()" value="-">
<input type="submit" onclick="multiplyNumber()" value="x">
<input type="submit" onclick="divideNumber()" value="÷">
<input type="submit" onclick="exponentiation()" value="^"><br>
<br>
<b>Calculation:</b><br>
<p id="result"></p>
<script src="calculator.js"></script>
</body>
</html>
Now, beyond that you can only return one value from a function so return val1, val2 is only going to return val2.
Also, since all your calculation functions do the same thing, but with different math, you can combine all of them into a single function and eliminate much of the duplication.
Next, you shouldn't be scanning the DOM for the same elements over and over within a function and instead get the references just one when the page loads and then just use those references over and over.
Finally, you should not be using inline event attributes, such as onclick as these are 25+ year old ways of doing event registration before there were any standards. Instead, you should be separating your HTML and JavaScript and hooking up your event handlers with .addEventListener().
Putting all those things in place, we get:
// By declaring these varaibles outside of the various functions that will
// use them, they are available (scoped) to all of them.
let val1 = null;
let val2 = null;
// Get the DOM element references you'll need just once
// rather than every time a function is executed.
const num1 = document.getElementById('number1');
const num2 = document.getElementById('number2');
// Set up event handlers in JavaScript, not HTML
// Here, we are using "event delegation" and just setting
// up one event handler at the document level for any click
// event within it. Those events will "bubble up" to the
// document and be handled here.
document.addEventListener("click", function(evt){
// We can check the element that triggered the event
// and see if it's one we really want to handle.
if(evt.target.classList.contains("operation")){
calculate(evt.target.value);
}
});
function calculate(operation) {
// When using parseInt, always supply the second (optional) radix argument
// which specifies what numerical base system you are working with, otherwise
// some values (i.e. 0x) could be processed as hex or base 8.
val1 = parseInt(num1.value,10);
val2 = parseInt(num2.value,10);
// switch checks the argument passed to it (operation in this case)
// and tests it against each case and if it matches, performs the code
// in that case branch
switch (operation){
case "+":
// Don't use .innerHTNL when the content you are working with isn't HTML
result.textContent = val1 + val2;
break;
case "-":
result.textContent = val1 - val2;
break;
case "*":
result.textContent = val1 * val2;
break;
case "/":
result.textContent = val1 / val2;
break;
case "^":
result.textContent = val1 ** val2;
break;
}
// There's no need to return anything from this function since
// you are putting the result into an element on the page.
}
<!doctype html>
<html>
<head>
<h1>Calculator</h1>
<body>
<!-- If you use type="number", it will avoid non-numeric data from being inputted -->
<input type="number" id="number1" placeholder="Enter number">
<input type="number" id="number2" placeholder="Enter number"><br>
<br>
<!-- type="submit" is for submitting form data. You aren't doing that
here and so should just be using type="button" -->
<input type="button" class="operation" value="+">
<input type="button" class="operation" value="-">
<input type="button" class="operation" value="*">
<input type="button" class="operation" value="/">
<input type="button" class="operation" value="^"><br>
<br>
<b>Calculation:</b><br>
<p id="result"></p>
<script src="calculator.js"></script>
</body>
</html>
I am only beggining my journey with Java Script! I was trying to create an input where I type in a number and after I press a button it would add the value to the var a = 0;
With the script I have written it returns the value as a string. Any ideas on how to make the value of the input be returned as a number? Thanks!!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JAVASCRIPT PRACTISE</title>
</head>
<body>
<div id="payment">
</div>
<button onclick="addToBal(10)" name="button">add 10 bucks</button>
<button onclick="subFromBal(10)" name="button">pay 10 bucks</button><br><br>
<input type="text" id="addInput" value="">
<button type="button" id="addSubmit" onclick="addValue()">add this amount of bucks</button>
<script>
var a = 0;
function addToBal(amtAdded) {
a += amtAdded;
document.getElementById("payment").innerHTML = a;
};
function subFromBal(amtSubstracted) {
a -= amtSubstracted;
document.getElementById("payment").innerHTML = a;
}; //THATS THE END OF THAT SECTION
function addValue(value) {
a += document.getElementById("addInput").value;
document.getElementById("payment").innerHTML = a;
};
</script>
</body>
</html>
Your issue is with:
document.getElementById("addInput").value;
This will return a string, meaning that when you add it, it will concatenate (glue) it to a (as an int+string gives a string), not add which is what you're after.
Thus, you can simply convert this string to a number by putting a + in front of it:
+document.getElementById("addInput").value;
See working example below:
var a = 0;
function addToBal(amtAdded) {
a += amtAdded;
document.getElementById("payment").innerHTML = a;
};
function subFromBal(amtSubstracted) {
a -= amtSubstracted;
document.getElementById("payment").innerHTML = a;
};
function addValue(value) {
a += +document.getElementById("addInput").value; // Add + here to convert string to number (ie: int, float etc)
document.getElementById("payment").innerHTML = a;
};
<div id="payment"></div>
<button onclick="addToBal(10)" name="button">add 10 bucks</button>
<button onclick="subFromBal(10)" name="button">pay 10 bucks</button><br><br>
<input type="text" id="addInput" value="">
<button type="button" id="addSubmit" onclick="addValue()">add this amount of bucks</button>
Input values are of type string. That's why string concatenation is happening. You have to convert the value to number to perform arithmetic operation. You can use Number or prefix the value with + to convert the string value to number:
var a = 0;
function addToBal(amtAdded) {
a += amtAdded;
document.getElementById("payment").innerHTML = a;
};
function subFromBal(amtSubstracted) {
a -= amtSubstracted;
document.getElementById("payment").innerHTML = a;
}; //THATS THE END OF THAT SECTION
function addValue(value) {
a += Number(document.getElementById("addInput").value);
//OR: using +
//a += +document.getElementById("addInput").value;
document.getElementById("payment").innerHTML = a;
};
<div id="payment">
</div>
<button onclick="addToBal(10)" name="button">add 10 bucks</button>
<button onclick="subFromBal(10)" name="button">pay 10 bucks</button><br><br>
<input type="text" id="addInput" value="">
<button type="button" id="addSubmit" onclick="addValue()">add this amount of bucks</button>
You can use Number()
reference
var num = "10";
num = Number(num); // 10 not "10"
you can use parseInt(document.getElementById("addInput").value) which will convert the string as integer.
I thinks you should understand about the string + number in JS.
http://jslearning.info/javascript-numbers/
You can only +/- 2 number, JS will convert to number.
you should not use Number in JS because it cause the speed in JS.
One more thing, if you HTML5, we can use input type is number
<input type="number" name="number">
Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">
I have a input field for user to input number. This number will be displayed in span tag as user is typing. And i would like to format this number in span tag with thousand separator.
Currently, it only show exactly what is typing without thousand separator:
JSFiddle
Here is my simplified code:
<!DOCTYPE html>
<html>
<head>
<script>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = x;
}
</script>
</head>
<body>
<form>
Price: <input type='text' id='frm_price'
onkeyup="charPreview()">
<span id="frm_price_preview"></span>
</form>
</body>
</html>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = decimalWithCommas(x);
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function decimalWithCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">    <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
An answer without loops.
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = numberWithCommas(x);
}
function numberWithCommas(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">    <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
See also accounting.js which handles this sort of thing quite nicely.
this is the code i came up with but all it does is this 1+1=11 i need it to do 1+1=2.
<head>
<script type="text/javascript">
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.form1.quantity.value;
two = document.form1.price.value;
c = one + two
document.form1.total.value = (c);
}
function stopCalc(){
clearInterval(interval);
}
</script>
</head>
<body>
<form name="form1">
Quantity: <input name="quantity" id="quantity" size="10">Price: <input name="price" id="price" size="10"><br>
Total: <input name="total" size="10" readonly=true><br>
<input onclick="startCalc();" onmouseout="stopCalc()" type="button" value="Submit">
</form>
</body>
of course this is a really simple form, but you get the idea
please help me tell what i'm doing wrong here
You need to use parseInt() to convert the string to an integer.
c = parseInt(one, 10) + parseInt(two, 10)
use this
c = parseInt(one,10) + parseInt(two, 10);
You need to convert the price values to numeric.
use parseFloat for price since it can have decimal values.
use parseInt with the radix.
e,g:
function calc(){
one = parseInt(document.form1.quantity.value, 10);
two = parseFloat(document.form1.price.value);
c = one + two
document.form1.total.value = (c);
}
You can use the + to convert a string to a number (integer or float)
c = +one + +two;
You can use this
one = document.form1.quantity.value/1;
two = document.form1.price.value/1;