javascript getElementById outside function does not work - javascript

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>

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>

I can't get setInterval to work for me

I have a function called start that is triggered when you push the start button. The start function calls another function called getRandomImage. I want getRandomImage to repeat every 5 seconds, but I just can't get the setInterval method to work for me. I've tried putting the interval on the start function, but that just causes it to fire off once, and doesn't repeat. I've tried putting the interval on the getRandomImages function, but then it doesn't do anything. Essentially I am trying to make a color blindness test that flashes a random image every 5 seconds until 30 images have passed or the user clicks a button. I've been banging my head against this for over 8 hours, and am really questioning my choice in programming languages right now, lol.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"
<title></title>
<link rel="stylesheet" href="ColorPerceptionTest.css">
</head>
<body>
<section>
<img src="Default.png" id="defaultimage">
<form>
<input type="button" id="Button1" value="" onClick="">
<input type="button" id="Button2" value="" onClick="">
<input type="button" id="Button3" value="" onClick="">
<br>
<input type="button" id="Start" value="Start" onClick="start()">
<input type="button" id="Help" value="Help" onClick="help()">
<br>
<p id="help"> </p>
</form>
</section>
<script>
var $ = function(id) {
return document.getElementById(id);
}
$("Button1").style.display = "none";
$("Button2").style.display = "none";
$("Button3").style.display = "none";
var imagesArray = ["3.gif", "05.gif", "5.gif", "6.gif", "7.gif",
"8.gif", "12.gif", "15.gif", "16.gif", "26.gif",
"29.gif", "42.gif", "45.gif", "73.gif",
"74.gif"];
var runTimer = setInterval(start, 5000);
function getRandomImage(imgAr, path) {
path = path || 'images/';
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
$("defaultimage").src = path + img;
$("Button1").style.display = "initial";
$("Button2").style.display = "initial";
$("Button3").style.display = "initial";
if(parseInt(img) < 8){
$("Button1").value = parseInt(img);
$("Button2").value = parseInt(img) - 2;
$("Button3").value = parseInt(img) + 1;
}else if(parseInt(img) > 7 && parseInt(img) < 29){
$("Button1").value = parseInt(img) - 2;
$("Button2").value = parseInt(img);
$("Button3").value = parseInt(img) + 1;
}else{
$("Button1").value = parseInt(img) - 5;
$("Button2").value = parseInt(img) - 9;
$("Button3").value = parseInt(img);
}
}
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var help = function (){
$("help").innerHTML = "This is a test designed to help you determine" +
" if you have a problem with seeing colors. When you press start, a series of " +
"random images will be displayed. You have 5 seconds to read the number and " +
"select the correct button.";
}
</script>
</body>
Try moving the setInterval call to a point where start is defined...
Your code works fine in this fiddle.
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var runTimer = setInterval(start, 5000);
Update: To make it more clear, had OP written function start() the posted code would have been properly hoisted. But, as he used a function expression, start is undefined when setInterval is called.
Another update: Here's a forked fiddle to correct the timer based on the button and the comments below.

textbox calculator with parsing function to arithmetic function

What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>
Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}
There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);

adding a result of a calculation to a span with javascript after a button is clicked

Hi I'm new to javascript and I would like you to help me figure out why I can't get the result of the random number generator to appear in the span tag after the user clicks a calculate button using the min and max number they entered. I believe there is nothing wrong with the random number function it's just when I want to use the random number function as an event handler for the onclick event for the button it doesn't work. well, what I did was, I made a function called answer to gather the users input and to use that input as a parameter for the the random number function that is being called inside the answer function.
Then I used the answer function as an event handler for the onclick thinking that it would have the result of the the random number generator and would apply that to the onclick. and I stored that in var called storage so I could place the result of the event in the span tag later.
Here is the js fiddle of the code. can you help me solve my problem by getting the result of the random_number function in to the span $("output") after the button $("calculate") click?
only pure javascript, no jquery please.
Thank you in advance for your help. and I'm sorry if I got terminology wrong and for bad spelling. http://jsfiddle.net/jack2ky/WDyMd/
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
var storage = $("calculate").onclick = answer;
var answer = function(){
var miny = $("min").value;
var maxy = $("max").value;
return random_number(miny, maxy);
}
$("output").firstChild.nodeValue = storage;
}
</script>
</body>
</html>
var storage = $("calculate").onclick = answer;
...
$("output").firstChild.nodeValue = storage;
These two statements are called on page load. What is happening is you are changing the value of variable storage but the statement var storage = $("calculate").onclick = answer;
is being called only once when the page loads. You need to update the answer when user clicks the button. So you can remove $("output").firstChild.nodeValue = storage; and update the answer function like:
var answer = function(){
var miny = parseInt( $("min").value );
var maxy = parseInt( $("max").value );
var ans = random_number(miny, maxy);
$("output").innerHTML = ans;
}
This should do it:
<!DOCTYPE html>
<html>
<head>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
$("calculate").onclick = function() {
var miny = $("min").value;
var maxy = $("max").value;
$("output").firstChild.nodeValue = random_number(miny, maxy);
}
}
</script>
</head>
<body>
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
</body>
</html>
$("output").firstChild.nodeValue = storage;
This line seems to be the problem because your output-Element has no firstChild. So the value gets written nowhere.
Just use
> $("output").nodeValue = storage;
edit: Tested this in jsFiddle - this is not the solutions as mentioned below!
If You are able to get your value in the variable storage
then you can simply render this value in span as HTML
$("#output span").html = storage;

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