1

Hey I'm really new to javascript and i just don't understand why it won't print on my document a number increasing every time i click on my button

<script type="text/javascript">

var x = 0;

function clicker(
    y = x+1
)
document.write(y)

return clicker();


</script>

<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
0

2 Answers 2

1

must be :

var x = 0;
function clicker(){
y = x+1;
document.write(y)
}

but, using document.write(y) will erase your button, to remedy this, you can create another element like <div id='status'></div> and use

//use this instead of document.write(y) 
var stat = document.getElementById("status"); 
stat.innerHTML = y;
Sign up to request clarification or add additional context in comments.

5 Comments

careful with this though, document.write will erase everything in your DOM and overwrite with the passed variable..which means you won't have your button anymore
a more suitable answer would be to add a div, and use document.getElementById('divid').innerHTML = y.
May I suggest to use <output> instead of <div>, and setting the value with stat.value = y.
Yes output is also good but it is not supported in internet explorer
According to mozilla ref it is supported in Internet explorer since version 10.
0

There are some problems with the script:

  • The syntax for the function is wrong, so the code won't run at all.
  • You can't use document.write once the page is loaded, then it will replace the entire page with what you write.
  • You are calculating a value that is one higher than a value that never changes, so it will only increase the first time, after that it just returns the same result.

Create an element where you can put the result, and increase the variable in the function so that the value changes each time.

<script type="text/javascript">

var x = 0;

function clicker() {
  x = x + 1; // or simply x++;
  document.getElementById('value').innerHTML = x;
}

</script>

<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
<div id="value"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.