javascript: Could not add two text inputs - javascript

This does not add the numbers instead gives NaN
<html>
<body>
<script>
function checkit()
{
x = document.getElementById("a");
x1 = parseInt(x);
y = document.getElementById("b");
y1 = parseInt(y);
alert("Answer is" + (x1 + y1));
}
</script>
<input type="text" id="a">
<input type="text" id="b">
<input type="button" onclick="checkit()">
</body>
</html>
Even tried document.getElementById("a").value;
Still gives NaN

document.getElementById returns the HTML element (an input, in your case), not its value. Try this instead:
x = document.getElementById("a").value;

Related

How to use html form input field's value in addition expression?

I have two text input fields in html form and need to add the field's value when add button is clicked.
I have used parseFloat function but they seem to be concatenated instead of addition.
<input type="text" id="x"/>
<input type="text" id="y"/>
<button id="add">ADD</button>
<h1 id="displayResult"></h1>
<script>
var x = document.getElementById("x");
var y = document.getElementById("y");
var add = document.getElementById("add");
var displayResult = document.getElementById("displayResult");
x = parseFloat(x);
y = parseFloat(y);
add.addEventListener('click', ()=>{
displayResult.innerHTML = x.value + y.value
})
</script>
You just need to parse the value not the element
x = parseFloat(x);// x here not value but the element
var x = document.getElementById("x");
var y = document.getElementById("y");
var add = document.getElementById("add");
var displayResult = document.getElementById("displayResult");
add.addEventListener('click', function() {
displayResult.innerHTML = parseFloat(x.value) +parseFloat(y.value)
})
<input type="text" id="x" />
<input type="text" id="y" />
<button id="add">ADD</button>
<h1 id="displayResult"></h1>
you need to get value from x & y first before using parseFloat
var x = document.getElementById("x");
var y = document.getElementById("y");
var add = document.getElementById("add");
var displayResult = document.getElementById("displayResult");
add.addEventListener("click", function () {
x = parseFloat(x.value); // here
y = parseFloat(y.value); // here
displayResult.innerHTML = x + y;
});

when i clicked the button '=', there's nothing happen

i am trying to make a simple calculator with javascript, but when i clicked the button '=' the result didn't appear.
<!DOCTYPE html>
<html>
<body>
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil" onclick="tambah">=</button>
<h2 id="hsl"></h2>
<script>
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
return a + b;
document.getElementById("hsl").innerHTML = tambah;
}
</script>
</body>
</html>
A number of problems with this
1) Collecting the input values from the textboxes before the user has had chance to type anything into them. You need to do that inside the event handler.
2) An inline event attribute (which was wrongly defined without the () anyway) and an eventlistener added in code. Only one is needed. The eventListener is generally considered the better way, e.g. for code maintainability and visibility.
3) Treating the values as strings and not numbers (e.g. if the code had otherwise been working, "4" + "4" would have returned "44"!)
4) returning from your tambah() function before the line which actually displayed the result. return returns from a function, it's not just for getting the result of a calculation.
This version corrects all those errors. You can run it to test it out:
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var sum = parseFloat(a) + parseFloat(b);
document.getElementById("hsl").innerHTML = sum;
}
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil">=</button>
<h2 id="hsl"></h2>
There are a few things incorrect with your code.
When you return a + b, there's no code executed after that return statement.
I've changed the code slightly, the vars a and b are now defined inside the function, and also made sure to use parseInt on your a and b - otherwise they would end up being concatenated as strings (meaning 1 + 2 would be 12 - wrong!)
var c = document.getElementById('hasil');
c.addEventListener('click', tambah);
function tambah()
{
var a = parseInt(document.getElementById('angkapertama').value);
var b = parseInt(document.getElementById('angkakedua').value);
var result = a + b;
document.getElementById("hsl").innerHTML = result;
}
<!DOCTYPE html>
<html>
<body>
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil">=</button>
<h2 id="hsl">answer here</h2>
</body>
</html>
A Simple example
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var sum = Number(a) + Number(b); //or
// var sum = parseFloat(a) + parseFloat(b);
document.getElementById("hsl").innerHTML = sum;
console.log(sum)
}
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil">=</button>
<h2 id="hsl"></h2>
However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way.
HTML:
<button id="hasil" onclick="tambah()">=</button>
SCRIPT:
function tambah() {
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var sum = Number(a) + Number(b); //or
// var sum = parseFloat(a) + parseFloat(b);
document.getElementById("hsl").innerHTML = sum;
console.log(sum)
}
content source here
Try this :
<!DOCTYPE html>
<html>
<body>
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil" onclick="tambah()">=</button>
<h2 id="hsl"></h2>
<script>
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
var sum = a + b;
document.getElementById("hsl").innerHTML = sum;
}
</script>
</body>
</html>

how to use a global variable inside a function in javascript?

I want to use global variables 'x, y' in the below funcion.
it works when I put the variables inside the function
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var x = document.getElementById('field_one').value
var y = document.getElementById('field_two').value
function calculator()
{
var p = x * y;
alert(x + " times " + y + " is " + p); //shows undefined times undefined is NaN
} // calculator()
</script>
</head>
<body>
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" value="" id="field_one"/> <br />
Number 2: <input type="text" value="" id="field_two"/> <br />
<input type="button" value="multiply them!" onclick="javascript:calculator()"/>
</form>
</body>
</html>
Your code works. But youre running in a race problem. You try to find Elements, before they are created:
var x, y;
window.onload = function() {
x = document.getElementById().value;
y = document.getElementById().value;
}
If your site is loading for a long time, the user may try to start the calculator script before x and y are set. Solution:
var x, y, calculator;
calculator = function() {
alert("please wait, until the site is completely loaded");
};
window.onload = function() {
x = document.getElementById().value;
y = document.getElementById().value;
calculator = function() {
alert(x + " times " + y + " is " + x * y);
};
}
The problem is as you want to get the value of x and y but them doesn't are setted value when function is called. If you want to use the variables many times, you need the create a function (I called setValues) that is responsible the set the value of x and y with the value of input, and always you need to get the values of input you can call it. Something like this:
var x;
var y;
function setValues() {
x = document.getElementById('field_one').value;
y = document.getElementById('field_two').value;
}
document.getElementById("calc").addEventListener("click", function() {
setValues();
var p = x * y;
alert(x + " times " + y + " is " + p);
}, false);
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" value="" id="field_one"/> <br />
Number 2: <input type="text" value="" id="field_two"/> <br />
<input type="button" id="calc" value="multiply them!" />
</form>
Positioning your script after the .html content guarantees everything is defined at the time you want the script working.
You can declare global variables from a local scope simply not using 'var' on declaration.
Do not forget to end each statement with a ';'
This way, your code is 100% functional:
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>This is a simple calculator.</p>
<form name="the_form">
Number 1: <input type="text" id="field_one"/> <br/>
Number 2: <input type="text" id="field_two"/> <br/>
<input type="button" value="multiply them!" onclick="readFields();"/>
<script type="text/javascript">
function readFields(){
x = document.getElementById('field_one').value;
y = document.getElementById('field_two').value;
calculator();
}
function calculator(){
var p = x * y;
alert(x + " times " + y + " is " + p); //shows undefined times undefined is NaN
} // calculator()
</script>
</form>
</body>
</html>

Recording XY coordinates of pixel onclick

I'm trying to a find a way where I can click on individual pixels and then the XY coordinates of the pixel will be recorded/printed. I found the code below online, but it only shows the coordinates of the last-clicked pixel. Is there a way to save/print the coordinates of all the pixels that I have clicked. I'm doing this for a Java applet and this would make it much easier for me to make polygons.
I would prefer the output (when I click the pixels) to be like this, so that I can just copy & paste into java:
int [] x={x1,x2,x3,x4,x...};
int [] y={y1,y2,y3,y4,y...};
Here is the code I found:
<html>
<head>
<script language="JavaScript">
function point_it(event){
pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("pointer_div").offsetTop;
document.getElementById("cross").style.left = (pos_x-1) ;
document.getElementById("cross").style.top = (pos_y-15) ;
document.getElementById("cross").style.visibility = "visible" ;
document.pointform.form_x.value = pos_x;
document.pointform.form_y.value = pos_y;
}
</script>
</head>
<body>
<form name="pointform" method="post">
<div id="pointer_div" onclick="point_it(event)" style = "background-image:url('image.jpg');width:2400px;height:1848px;">
<img src="point.gif" id="cross" style="position:relative;visibility:hidden;z-index:2;"></div>
You pointed on x = <input type="text" name="form_x" size="4" /> - y = <input type="text" name="form_y" size="4" />
</form>
</body>
</html>
<html>
<head>
<script language="JavaScript">
var x = [];
var y = [];
function point_it(event) {
pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("pointer_div").offsetTop;
document.getElementById("cross").style.left = (pos_x - 1);
document.getElementById("cross").style.top = (pos_y - 15);
document.getElementById("cross").style.visibility = "visible";
x.push(pos_x);
y.push(pos_y);
document.getElementById("form_x").innerHTML = x;
document.getElementById("form_y").innerHTML = y;
};
function remove_it() {
x.pop();
y.pop();
document.getElementById("form_x").innerHTML = x;
document.getElementById("form_y").innerHTML = y;
}
</script>
</head>
<body>
<form name="pointform" method="post">
<div id="pointer_div" onclick="point_it(event)" style="background-image:url('image.jpg');width:2400px;height:1848px;">
<img src="point.gif" id="cross" style="position:relative;visibility:hidden;z-index:2;">
</div>
You pointed on
<br>x = <span id="form_x"></span>
<br>y = <span id="form_y"></span>
<br>
<button onclick="remove_it()">remove last</button>
</form>
</body>
</html>

JavaScript Calculating Value of Addition

I am unable to add 2 numbers taking from inputs.
<script>
x = document.getElementById('input1').value;
y = document.getElementById('input2').value;
z = Number(x)+ Number(y);
document.getElementById('submit1').addEventListener("click",alpha);
function alpha(){document.getElementById('div1').innerHTML="The answer is" + z;}
</script>
I need to do this with help of javaSCript only.
You could try something like this:
document.getElementById('submit1').addEventListener("click", function(){
// I suppose that the values you insert in your inputs are
// integers. Otherwise, you could use the parseFloat(value, 10)
// to parse float =s.
var x = parseInt(document.getElementById('input1').value);
var y = parseInt(document.getElementById('input2').value);
// Add the numbers
var z = x + y;
// Set the result in the selected div.
document.getElementById('div1').innerHTML="The answer is" + z;
});
You could try to run the following snippet:
document.getElementById('submit1').addEventListener("click", function(){
// I suppose that the values you insert in your inputs are
// integers. Otherwise, you could use the parseFloat(value, 10)
// to parse float =s.
var x = parseInt(document.getElementById('input1').value);
var y = parseInt(document.getElementById('input2').value);
// Add the numbers
var z = x + y;
// Set the result in the selected div.
document.getElementById('div1').innerHTML="The answer is " + z;
});
<input type="text" id="input1"/>
<br/>
<input type="text" id="input2"/>
<br/>
<div id="div1">
</div>
<br/>
<button id="submit1">submit</button>
You want to use parseInt() to turn a string into an int.
<html>
<head>
<title></title>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("button").addEventListener("click",function(){
var a = parseInt(document.getElementById("input1").value);
var b = parseInt(document.getElementById("input2").value);
document.getElementById("output").innerHTML="The Answer is "+(a+b);
},false);
});
</script>
</head>
<body>
<input id="input1" type="text"/>
<input id="input2" type="text"/>
<button id="button">Add</button>
<div id="output"></div>
</body>
</html>

Categories

Resources