Value returned as a string - javascript

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">

Related

Button function calling another function

im just a beginner and i want to find the answer to this problem.
This is my html code.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name = "step" id = "step">
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
This is my javascript code.
var step = document.getElementById("step").innerHTML;
parseInt(step);
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
What I did is to call the function matchHouses(step) by the click of the button. But the output is always 1. I also put parseInt to the step id as it is string but it is still doesnt work. I was expecting an output of 1+5 if the input is 1, 1+5+5 if the input is two and so on. How do I make it work?
The two key things are that a) parseInt won't do the evaluation "in place". It either needs to be assigned to a variable, or the evaluation done as you're passing it into the matchHouse function, and b) you should be getting the value of the input element, not the innerHTML.
Here are some additional notes:
Cache all the elements first.
Add an event listener in your JavaScript rather than using inline JS in the HTML.
No need to have an additional variable for counting - just decrement step until it reaches zero.
Number may be a more suitable alternative to parseInt which requires a radix to work properly. It doesn't always default to base 10 if you leave it out.
Assign the result of calling the function to demo's textContent (not innerHTML as it is just a simple string, and not a string of HTML markup.
// Cache elements
const step = document.querySelector('#step');
const demo = document.querySelector('#demo');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
function matchHouses(step) {
let out = 1;
while (step > 0) {
out += 5;
--step;
}
return out;
}
function handleClick() {
// Get the value of the input string and
// coerce it to a number
const n = Number(step.value);
demo.textContent = matchHouses(n);
}
<body>
<input type="text" name="step" id="step">
<button type="button">Submit</button>
<p id="demo"></p>
</body>
I rewrote your code like this:
let step = 0;
function handleInput(e){
step = e.value;
}
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name="step" id="step" onkeyup='handleInput(this)'>
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>

The Adding function doesn't work in JavaScript

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>

How to check and return a message if no value entered

I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>

Javascript: why am i getting NaN even after using parseInt() function?

I want to create a HTML page that can do the following tasks:
Take a number from the user
Calculate a multiplication table and show it below the calculate button
Format of multiplication table should be like this, but on the same page and below the calculate button:
5
10
15
20
25
30
35
40
45
50
But I am getting NaN error, and also need help with how to get table displayed like this on the same page, please help and bear with my newbie mistakes :-)
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable(nn)
{
for(i=1; i<=10; i++)
{
document.getElementById("t1").innerHTML = nn*i;
}
return true;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable('n')">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
<script type="text/javascript">
m = "num".value;
n = Number(m);
</script>
</body>
</html>
There's no mystery
m = "num".value;
here, m = undefined, because the string "num" has no property called value, i.e. it's undefined
n = Number(m);
Number(undefined) === NaN - because undefined is not a number
edit: also your onclick is called like this - createTable('n')
same problem, 'n' is not a number, it's a string .. 'n' * anything == NaN
There some problem with your program just see this one
<!doctype html>
<html>
<head>
<title>Multiplication Table</title>
<script type="text/javascript">
function createTable()
{
var nn = document.getElementById("num").value;
var str="<table>";
for(i=1; i<=10; i++)
{
str+="<tr><td>" + nn + "*" + i +" = " + (nn*i) + "</td></tr>";
}
str+="</table>";
document.getElementById("t1").innerHTML = str;
}
</script>
</head>
<body>
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" id="num" name="num" size=10></center><br />
<center><button type="button" onclick="createTable()">Calculate</button></center>
</form>
<center><p id="t1"></p></center>
</body>
</html>
You are converting a value to a number, but it's at the wrong time, and it's the wrong value. Then you don't even use the result.
This code:
m = "num".value;
n = Number(m);
is executed when the page loads, so that's before the user has had any chance to enter any number. It doesn't use the field where the user could enter a number, it only uses the string "num". As the string isn't the input element, it doesn't have a property named value, so m gets the value undefined. Turning that into a number gives you NaN, but that's not even the NaN that you get in the output, because the value of n is never used.
This code:
onclick="createTable('n')"
doesn't use the variable n, it uses the string 'n'. That is what gives you the NaN in the output, because that is what you get when you try to use the string in the multiplication. I.e. 'n' * i results in NaN.
To get the value that the user entered, you should get it at the time that the user clicks the button. Put the code in a function so that you can call it at that time. Use the getElementsByName method to locate the element:
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
When the user clicks the button, call the function to get the value and send it to the function that creates the table:
onclick="createTable(getValue())"
In your code where you create the table, you should put the items together and then put them in the page. If you put each item in the element, they will replace each other and you end up with only the last one. Also, you would want to put an element around each item, otherwise you end up with just a string of digits:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
Demo:
function createTable(nn) {
var str = '';
for(var i = 1; i <= 10; i++) {
str += '<div>' + (nn * i) + '</div>';
}
document.getElementById("t1").innerHTML = str;
}
function getValue() {
var m = document.getElementsByName("num")[0].value;
return Number(m);
}
<h1><center>Assignment No.4</center></h1>
<h4><center>Please Enter Number for Table and press the button</center><h4>
<form>
<center><input type="text" name="num" size=10></center><br />
<center><button type="button" onclick="createTable(getValue())">Calculate</button></center>
</form>
<center><p id="t1"></p></center>

How can I ADD form values using javascript?

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;

Categories