how to use a global variable inside a function in javascript? - 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>

Related

How do I make variables change outside functions in javascript?

I am a beginner with Javascript/programming and I am trying to make the "demo2" id change with the 5, 10 or 15 variable chosen in the functions (trigger by the buttons), but it keeps showing "0". What do I have to do?
<!DOCTYPE html>
<html>
<body>
<button onclick="alternative1()">5</button>
<button onclick="alternative2()">10</button>
<button onclick="alternative3()">15</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
var x = 0;
var y = 0;
function alternative1() {y = x + 5;
document.getElementById("demo").innerHTML = "You have chosen " + y;
}
function alternative2() {y = x + 10;
document.getElementById("demo").innerHTML = "You have chosen "+ y;
}
function alternative3() {y = x + 15;
document.getElementById("demo").innerHTML = "You have chosen "+ y;
}
document.getElementById("demo2").innerHTML = y;
</script>
</body>
</html>
You can’t access variables declared inside a function from outside a function. The variable belongs to the function’s scope only, not the global scope.
It is normal that there is zero because in 'y' there is zero and no operation performed on y.
I hope that this answer will help you to understand what you have done.
You don't need 3 functions for this. You can do it with 1.
<!DOCTYPE html>
<html>
<body>
<button onclick="alternative(this)">5</button>
<button onclick="alternative(this)">10</button>
<button onclick="alternative(this)">15</button>
<p id="demo"></p>
<script>
function alternative(obj) {
document.getElementById("demo").innerHTML = "You have chosen " + obj.innerHTML;
}
</script>
</body>
</html>
Happy learning
You need to change 'demo2 inner' after every operation and need to add new value to 'y' current value (use +=)
var x = 0;
var y = 0;
function alternative(param) {
y += x + param;
document.getElementById("demo").innerHTML="You have chosen "+ param;
document.getElementById("demo2").innerHTML = y;
}
<!DOCTYPE html>
<html>
<body>
<button onclick="alternative(5)">5</button>
<button onclick="alternative(10)">10</button>
<button onclick="alternative(15)">15</button>
<p id="demo"></p>
<p id="demo2"></p>
</body>
</html>

javascript getElementById outside function does not work

I am relatively new to javascript and made this simple guess the number program. My question is this:
Why does it only work if:
var myNumber = document.getElementById("myNumber").value;
is defined within the function. I thought that if it was defined outside the function it will have "scope to b used within it?
Thank you for any help.
<p> Enter your number 1-10 <input id="myNumber" type="text"> </p>
<button id="btn1">Go</button>
<script type="text/javascript">
document.getElementById("btn1").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var number = parseInt(myNumber);
var count = 1;
var computerGuess = Math.floor((Math.random() * 10) + 1);
while (computerGuess !== number) {
computerGuess = Math.floor((Math.random() * 10) + 1);
count++;
}
alert("you guessed it" + " in " + count + " guesses");
}
</script>
When you will use document.getElementById in global scope it will return undefined if
the script is above the element which you wanna access. Because it can get element by id before it is created
Solution 1. Use all your script tags at last of all elements
Solution 2. use this way
<!DOCTYPE html>
<html>
<body>
<script>
var globalElm;
function start(){
globalElm = document.getElementById('elm')
}
setTimeout(start,50);
</script>
<div id="elm"></div>
</body>
</html>

javascript: Could not add two text inputs

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;

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>

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Categories

Resources