Pergunta

Code below is correct. But it doesn't work in my browser. I have no clue why my browser isn't counting.

<SCRIPT LANGUAGE="JavaScript">
var count = 0;
var countEl = document.getElementById("count");

function plus(){
    count++;
    countEl.value = count;
}

function minus(){
    count--;
    countEl.value = count;
}
</SCRIPT>

<div id="input_div">
    <input type="text" size="25" value="0" id="count">
    <input type="button" value="-" id="moins" onclick="minus()">
    <input type="button" value="+" id="plus" onclick="plus()">
</div>
Foi útil?

Solução

At the time the script is running there are no elements as they haven't loaded yet.
Easy fix would be to just move the script to the bottom:

<div id="input_div">
    <input type="text" size="25" value="0" id="count">
    <input type="button" value="-" id="moins" onclick="minus()">
    <input type="button" value="+" id="plus" onclick="plus()">
</div>

<script type="text/javascript">
var count = 0;
var countEl = document.getElementById("count"); // now this is available

function plus(){
    count++;
    countEl.value = count;
}

function minus(){
    count--;
    countEl.value = count;
}
</script>

Outras dicas

As I can see it u have to small errors in ur code. First u try to search for an element before it's in the dom. So this "document.getElementById("count")" will not return the element.

The other part is for a onclick to work u should ad a ";" after the function name like this.

<input type="button" value="+" id="plus" onclick="plus();">

But then the element still wont get updated by clicking the button. So therefore u should include the script and rewrite it like this. What I have done is binding the onclick event on the element in the javascript at the same time as I create the function. I also changed so the variables are declared with one var and the code is wrapped in a self executing function so nothing is declared in the global scope. I hope my answer helped u some, good luck!

HTML

<div id="input_div">
    <input type="text" size="25" value="0" id="count">
    <input type="button" value="-" id="moins">
    <input type="button" value="+" id="plus"">
</div>
<script>
(function(document){
var count = 0,
    countEl = document.getElementById("count"),
    minus = document.getElementById("moins"),
    plus = document.getElementById("plus");   
plus.onclick = function(){
    count++;
    countEl.value = count;
}
minus.onclick = function(){
    count--;
    countEl.value = count;
}
}(document));
</script>

Here is a link to my fiddle to test the code.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top