I am trying to make a simple function that increases the number value of one variable by the value of another variable.
( a = 2 ) ( b = 5 ) ( a = a + b )
document.write(a) gives ( 2 ), which is ( a ) but unchanged. I expected to get ( 7 ). What am I doing wrong?
var a = 2;
var b = 5;
function add() {
a = a + b;
}
document.write(a)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<input type="button" value="add" onclick="add()">
</div>
</body>
</html>
your document.write(a) write before add function calls so no change. You need to update the element in the inside function
You need to add an HTML element to show your data and use innerHTML to set it
var a = 2;
var b = 5;
function add() {
a = a + b;
// instead of document.write, find the element that you want to hold your element
// and set it's inner html to your value
//this will update the DOM
document.getElementById("myHeader").innerHTML = a;
}
<input type="button" value="add" onclick="add()">
<!-- add an element to hold your result -->
<h1 id="myHeader">Hello World!</h1>
Make the neccsary changes in the code,
You have to write the document.write() at the time you make the function call .
In your case : You wrote it in body so whenever the page load at that time it takes the inital value of a and when you make the function call , the value of a get increased but not print .
<!DOCTYPE html>
<html>
<head>
<script>
var a = 2;
var b = 5;
function add() {
a = a + b;
document.write(a)
}
</script>
</head>
<body>
<div>
<script></script>
<input type="button" value="add" onclick="add()">
</div>
</body>
</html>
your document.write(a) function call is only run the first time the page loads. when you click the button, that only runs the add() function but does not rerun document.write(a)
Related
I am trying to capture time from a stopwatch within a browser and display the times (laps) below. To do this, I am intending to create an unordered list from an array within a JavaScript file.
Here is the JS:
laps = []:
function show() {
$time = document.getElementById('time');
document.getElementById("capture").setAttribute("disabled","disabled"); // disable capture button until start
update();
}
function update() {
$time.innerHTML = formatTime(time());
displayLaps();
}
function displayLaps() {
if (laps == "" || laps.length == 0) {
return false; // stop the function if the value is empty
}
var inner = `Lap ${lap_count} :${formatTime(laps[lap_count-1])}`;
document.getElementById("laps").innerHTML += '<li>' + inner + '</li>';
}
And the associated html:
<!doctype html>
<html lang="en">
<head>
</head>
<body onload="show()">
<div>Time: <span id="time"></span></div>
<button onclick="onStart()" id="start" style="width:150px">Start</button>
<button id="capture" style="width:150px">Capture</button>
<div id="laps"><ul></ul></div>
<script src=".\stopwatch.js"> </script>
</body>
</html>
I am getting peculiar behaviour though. It seems that the += operator on the last line of code keeps adding rows that display the last array vaue (see below), whereas replacing this with a simple = operator just creates a single row that is then replaced every time a new lap value is added to the array.
I'm obviously missing something, but would appreciate some guidance, if possible.
Many thanks!
HTML code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="score-board.css">
<title>Score Board App</title>
</head>
<body>
<div id="playersscores">
<span id="p1score">0</span><span> To </span> <span id="p2score">0</span>
</div>
<p>Playing to <span id="score">5</span></p>
<input type="field" value="5" ></input>
<button id="p1clicked">Player one</button>
<button id="p2clicked">Player two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score-board.js"></script>
</body>
</html>
Javascript is :
Whenever this code is loaded :
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score (player_result) {
//var score = parseInt(player_result.innerText) + 1;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener("onclick", increment_score(p1result))
Whenever this code is loaded in a browser, the span showing the result for player 1 is showing one directly without clicking on player 1 button. i'm not sure what is wrong with the event listener im using.
The event is click instead of onclick
The event listener should be a reference to the function itself, not the result of a function call (which increments the score by 1)
Inside the function, you can access the button with this:
The code could look like this:
function increment_score() {
var player_result = this;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener('click', increment_score);
Use click event not onclick
You pass result of function not instead reference to function
If you need pass parameters to event handler - you can use bind:
p1clicked.addEventListener("click", increment_score.bind({result: p1result, inc: 1 }) )
p2clicked.addEventListener("click", increment_score.bind({result: p2result, inc: 2 }) )
function increment_score () {
var score = parseInt(this.result.innerText) + this.inc;
this.result.innerText = score;
}
[ https://jsfiddle.net/6vw8ay3x/ ]
You have a couple problems there. First, when calling the addEventListener function, you need to specify just "click", not "onclick". Secondly, when you pass the function to addEventListener, you just want it to be a reference to the function not an actual function call. The following changes will net you the result you are seeking.
function increment_score () {
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
}
p1clicked.addEventListener("click", increment_score);
But since you want to be able to use the same function for multiple players, then I would suggest adding the "onclick" handler to the HTML which will allow you to pass the element you want to increment. Then your HTML code would look like this:
<button id="p1clicked" onclick="increment_score_with_param(p1result);">Player one</button>
<button id="p2clicked" onclick="increment_score_with_param(p2result);">Player two</button>
and your javascript would be:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score_with_param (player_result) {
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
window.onload = function(){
var p1result = document.querySelector('#p1score');
var p2result = document.querySelector('#p2score');
var p1clicked = document.querySelector('#p1clicked');
p1clicked.addEventListener("click", function(e){
e.preventDefault();
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
});
}
My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?
var a = 5;
var b = 16;
var c = 27;
function reset(){
a = 0;
b = 0;
c = 0;
}
My html code to call the function:
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
</form>
</html>
Javascript code to show the variables:
function display(){
document.write("A is equal to " + a + "<br/>");
document.write("B is equal to " + b + "<br/>");
document.write("C is equal to " + c );
}
Html to display the variables
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
</form>
</html>
change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.
http://www.w3schools.com/jsref/met_form_reset.asp
There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global variable.
That can`t work, because you are asserting that variables in function scope. But your variables are currently stored in global scope (window), so this code will work:
var a = 5;
function reset() {
console.log(window.a); // 5
window.a = 10;
}
reset();
console.log(a); // 10
I have created 3 variables a,b,c. I have assigned values to a and b and have also made a textbox. What I want to do is enter the name of a the variable in the textbox and click the button, then the textbox should should display the value assigned to that variable. It maybe very simple but I do not know what I did wrong.
Here is the FIDDLE
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=c;
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
Your easiest choice would be to assign your variables to a object, like this:
var vars;
function display() {
var value = document.getElementById("b1").value;
vars = {
a: 2,
b: 3,
c: value
}
if (vars.hasOwnProperty(value)) { // If the entered value is a variable name
document.getElementById("demo").innerHTML = vars[value]; // Display the variable
} else { // Otherwise
document.getElementById("demo").innerHTML = value; // display the value
}
}
Working example
The if/else can be replaced with this, to make it a little shorter:
document.getElementById("demo").innerHTML = vars.hasOwnProperty(value) // If
? vars[value] // Then
: vars.c; // Else
Try this way:
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
if(c==a){
document.getElementById("demo").innerHTML='a';
}
if(c==b){
document.getElementById("demo").innerHTML='b';
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update value.</p>
</body>
</html>
DEMO
What you are looking for is the eval() method (Which, do a quick google search, it is not recommended).
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=(eval(c));
// if user enters b in the input field, then the html in demo will be 3
// if user enters a in the input field, then the html in demo will be 2
}
</script>
Again, not recommended!
If you declare variables directly in you script-element they are created as properties of the window-object and can be accessed as such. Thus just update your script like the following to show the contents of the variables:
<html>
<head>
<script>
var a = 2, b = 3;
function display() {
var strVarName = document.getElementById('b1').value;
if(window.hasOwnProperty(strVarName)) {
document.getElementById('demo').innerHTML = window[strVarName];
} else {
document.getElementById('demo').innerHTML = 'Variable ' + strVarName + ' does not exist.'
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
This won't work if you declare the variables inside the display function, but this doesn't seem like a thing you would do if this code were to be used in a system to anything beside this one simple function.
I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
function traverse(){
output.innerHTML+='Test'; // Nothing happens !
}
function check() {
var keywords = document.getElementById('text').value.split(" ");
for (var i=0; i < keywords.length; ++i) {
traverse_tree()
}
}
</script>
</head>
<body onload ="init()">
<input id="text" type="text" size="60" value="Type your keywords here" />
<input type="button" value="Display the text 'Test'" onclick="check();" />
<div id="output">
</div>
</body>
</html>
thanks,
Bruno
Perhaps because the function is called traverse() and you're calling traverse_tree()?
Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
document.getElementById('output').innerHTML+='Test';
}
You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {
// Cache the node to be updated here
var node = document.getElementById(nodeId);
// This is the function that "traverse()" will call. Return this function,
// which will assign it to the variable traverse.
return function () {
node.innerHTML += 'test';
};
// Execute the function with the id of the node to cache, i.e. output
}('output'));