so I have a js file, lets call it foo.js and it has a variable count; this count is what I want to display in a textbox on the html end, which is a separate file.
How can I make the textbox, reference the variable which constantly is updated per minute?
Here is what I tried so far,
<script type="text/javascript">
var elem = document.getElementById("count");
elem.value = countVal;
</script>
Where I want to show it in HTML:
Shapes:
if I set elem.value to 5, or hello world, it works, but I want to set it to the constantly updating js value in a seperate page. I also tried creating a function in my js file, where I return the variable, and then calling that function in the html tag, but that did not work either.
I am new to JS, and I would appreciate your help.
Thank you.
Edit:
THIS IS NOT for a TIME INTERVAL, I have a variable, that based on some drawings, counts the shapes drawn, and I want to bring that to front end. That count.
MORE CODE:
my function in the .js file
function getShapeNumbers(){
return shapeCount;
}
<script type="text/javascript">
var elem = document.getElementById("shapeCount");
elem.value = getShapeNumbers();
</script>
where I want it displayed
Shapes:<input type="text" size="25" style="width:50px;" id ="shapeCount" />
it returns undefined in the textbox even if I change my function to return 50, it shows undefined. And if I just elem.value to 50, then that works. I want it set to my global variable
Probably your js file is not loaded by the browser yet when you run the code elem.value = newvalue.
Run this only after all document html content be loaded:
window.onload = function(){
document.getElementById('shapeCount').value = shapeCount;
};
Also, consider updating directly input when updating variable.
jsFiddle: http://jsfiddle.net/bx4SU/
Related
https://stackoverflow.com/a/43635720
On this answer, it says to define a variable (window.parentPage = true;) in the index.html page. How can I go about doing this?
You would need to define the variable using JavaScript. You can embed some JavaScript in the HTML file by encasing it in a script tag like so:
<script type="text/javascript">
window.parentPage = true;
</script>
First you need to clearly realize your reason... what you want to achieve.
After that defining that to yourself:
First option:
You can store/save some data as stated on the link you added to your question inside a tag, like that:
<script>
var myLittleBox = "box content";
</script>
And access it later like:
<script>
myLittleBox = myLittleBox + " extra content";
console.log(myLittleBox);
//this will print "box content extra content"
</script>
You need to use the tag to access the javascript environment.
Second option:
You can save/store data with pure HTML using an with type "hidden" to not show it on screen as an input box, and changing it's value, like that:
<input type="hidden" value="box content">
But this way you'll not be able to access the data directly without aid of javascript code, unless you send this input somewhere reachable as GET or POST within a and recover it getting the respective GET or POST.
Javascript variables:
https://www.w3schools.com/js/js_variables.asp
Ex: https://www.w3schools.com/js/tryit.asp?filename=tryjs_variables
HTML input:
https://www.w3schools.com/tags/tag_input.asp
HTML form handling:
https://www.w3schools.com/php/php_forms.asp
You're probably trying to understand the first option, but you question do not make that clear. Anyway, good studies.
Whatever you do you will have to use JavaScript in order to access the variable. An orthodox way of doing it that is not mentioned yet is using an data-attribute inside the html and than you access it by JavaScript:
const attributeName = 'data-parentPage';
const setup = () => {
let parentPageBool = document.querySelector(`html[${attributeName}]`).getAttribute(attributeName);
console.log(parentPageBool)
};
window.addEventListener('load', setup);
<html data-parentPage="true">
</html>
EDIT:
Okay, gonna try to use as little code as possible to explain my problem.
I have a select dropdown menu that has a function changetext() tied to it. Whenever a value is selected in the dropdown menu, text inside a tag is changed.
The script to the function is stored in an external js file and is placed at the bottom of my html file.
Inside the js file is something like this.
var selectormenu = document.getElementById("selector");
var spanTag = document.getElementById("texthere");
function changetext(){
if(selectormenu.value == "one"){
spanTag.innerHTML = "one";
}
}
By using this js file, I get a TypeError in my browser console. However, if I place var selectormenu and spanTag inside the function, the script works.
EDIT: Since the question case sensitivity was fixed, I am adjusting my answer. You need the DOM element to already be created, because document.getElementById needs to have something to select. Then, your function needs to be named before the parentheses. Finally, you need to call the function, because it won't run unless it's called.
<div id="divid>Hello World!</div>
<script>
var soandso = document.getElementById("divid");
function statsChange() {
soandso.innerHTML = "123";
}
statsChange();
</script>
I need help with my website, or what you want to call it.
The idea is that i have a number, and if a button gets clicked, my number gets added by 1. I have searched the web for hours, and I just can't figure it out. As you can see, I'm pretty new to javascript. I hope you guys would take some time out of the day to help me. Thanks.
<!DOCTYPE html>
<html lang='en'>
<head>
<title></title>
<meta charset='utf-8'>
<link rel="stylesheet" href="buttonClicker" type="text/css" />
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function oneClick(){
var clicks += 1;
}
document.write(clicks);
</script>
<br>
<input type="button" value="Click Me!" onclick="oneClick()" />
</body>
</head>
Remove var from your line var clicks += 1. var is only used when initializing the variable, which you already did outside of your oneClick function.
#ElliotBonneville is correct, but I'll explain some more about why that works. Using var makes something have limited scope to the containing function, or, if it is not in a function, the window. This means that if you use var inside of a function, you won't be able to access that variable outside of that function. E.g.:
function makeScopedVar(){
var scopedVar='hi';
}
makeScopedVar();
console.log(scopedVar);//will log "undefined" or "null" to the console, not "hi"
when NOT using var to declare the variable, it is declared globally, E.g:
makeGlobalVar(){
globalVar='hi';
}
makeGlobalVar();
console.log(globalVar);//will log "hi" to the console
Also, variables in functions, if scoped, are completely different than out of function variables. Let me explain:
var trickyVar='hi global';//this uses var, but it isn't in a function so the variable is still created globally
function makeScopedVar(){
var trickyVar='hi scoped';
}
makeScopedVar();
console.log(trickyVar);//will log "hi global" to the console
As you can see, the function creates a scoped variable because of var, and the other one is global so it generates a completely different variable. In your code, the code inside of the function using var clicks+=1 generates a scoped clicks variable and increments it, but this is seperate from the other variable and therefore it doesn't work as expected. Here is how your code should look:
<script type="text/javascript">
var clicks = 0;
function oneClick(){
clicks += 1;
alert(clicks);
}
</script>
I removed document.write and replaced with alert it because...document.write is bad for many reasons. In this example, it would remove the whole page. I also placed it INSIDE the function because otherwise, it would run when the page loads and that is all. Here's a working codepen (inline handlers don't work in jsfiddle): http://codepen.io/anon/pen/ziltn
The reason the the other answer wasn't working for you was because the console.log/alert was outside of the function.
EDIT:
If you would rather have the number of clicks be in an element on the page rather than in an alert box, you simply have to add an element to the page and modify it's content. Include this HTML in the page:
<div id="clickoutput">0</div>
and replace alert(clicks) with document.getElementById('clickoutput').textContent=clicks
There are two problems in your code:
First, you redefine the clicks variable inside oneClick() function. Since the clicks variable is defined in your first script line, you don't need to define it again inside the function, you can just use it: clicks += 1.
The second problem is that document.write() will replace the content of your html document with what you pass to it, which is not what you want. You need to define a html element that will hold your value, and then write the number to it:
In your html:
<div id='clicks'>0</div>
and in your script:
document.getElementById('clicks').innerHtml = clicks
Edit: Thanks Markasoftware
I'm just started to learn HTML. Doing an alert() on one of my variables gives me this result [object HTMLInputElement].
How to get the data, that were added in text field, where my input type is text?
Say your variable is myNode, you can do myNode.value to retrieve the value of input elements.
Chrome Developer Tools has a Properties tab which shows useful DOM attributes.
Also see MDN for a reference.
If the element is an <input type="text">, you should query the value attribute:
alert(element.value);
See an example in this jsFiddle.
Also, and seeing you're starting to learn HTML, you might consider using console.log() instead of alert() for debugging purposes. It doesn't interrupt the execution flow of the script, and you can have a general view of all logs in almost every browser with developer tools (except that one, obviously).
And of course, you could consider using a web development tool like Firebug, for instance, which is a powerful addon for Firefox that provides a lot of functionalities (debugging javascript code, DOM inspector, real-time DOM/CSS changes, request monitoring ...)
It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
My code example:
bank.html
<!doctype html>
<html>
<head>
<title>Transaction Tracker</title>
<script src="bank.js"></script>
</head>
<body>
<div><button onclick="bitch()">Press me!</button></div>
</body>
</html>
Javascript code:
bank.js
function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }
function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);
you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about.
So simple solution is to change either the variable name or the id or class name.
change:
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
to
$("input:text").change(function() {
var value=$("input[type=text].selector").val();
alert(value);
});
note: selector:id,class..
<input type="text" id="name">
and in javascript
var nameVar = document.getElementById("name").value;
alert(nameVar);
<input type="text" />
<script>
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
</script>
use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.
When you get a value from client make and that a value for example.
var current_text = document.getElementById('user_text').value;
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200 ){
var response = http.responseText;
document.getElementById('server_response').value = response;
console.log(response.value);
}
SO i am trying to get the value or the contents of an HTML text box. I have tried various types of methods but none of them work. According to the debugger , the code stops at getelementbyid method. The commented lines are the methods that I have already tried. Some of them return null while some of them return NaN and most of them just return a blank page.
help is much appreciated.
<html>
<head>
<script type="text/javascript" >
function calculateit(){
document.open();
var number = document.getElementsByName('xyz')[0].value
//var number = document.getElementsByName("xyz").value;
//var number = document.getElementsByName('xyz').value;
//var number = document.getElementsByName("xyz");
//var number = document.getElementsByName('xyz');
//var number = document.getElementsById("xyz").value;
//var number = document.getElementsById('xyz').value;
//var number = document.getElementsById("xyz");
//var number = document.getElementsById('xyz');
//var number = document.form1.xyz.value; //form 1 was my form name and/or id
document.writeln(number);
var newtemp = 0;
var newtemp = tempera *9/5+32;
document.write(newtemp);
}
</script>
</head>
<body>
<input type="text" id="xyz" name="xyz">
<button title="calculate" onclick="calculateit()">calculate </button>
</body>
</html>
You're using the wrong method. The two widely supported methods for javascript are "getElementsByTagName" and "getElementById". Note exactly how "getElementById" is spelled. It is meant to get one element with the exact id that you specify. "getElementsByTagName" gets all elements of a certain tag...such as "div". When using "getElementById", you don't to index it or anything - it either returns null (can't find) or the exact element reference. From there, since it is a textarea, you can use ".value" to get the current value, like you already are.
ALSO:
You probably shouldn't use "document.write" or any of its related write methods AFTER the page has been rendered. In your example, that's exactly what you're doing, so once you get the ".value" stuff working, I would change that. The point is that "document.write" is more for during page rendering...so if you had javascript inline with the HTML body or something. Something like:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("testing");
</script>
</body>
</html>
would be fine, but still not preferred. The fact that you have it in a function, that is called on a button click, means it is not during page render, and shouldn't be used. A more practical approach is to have a <div> on the page and add text to it when necessary, using something like ".innerHTML". That way, things are dynamic and not overwritten in the actual document.
It's getElementById, not getElementsById.