1

I have a script with a javascript variable and a button, now everytime I press this button I would like the variable to raise by one, I have tried as you can see in the script below, but there are some issues, the number doesn't show and the number isn't raised by one every time the button is clicked, what is wrong?

javascript:

var nativeNR = 1;

function addOne() {
    nativeNR = nativeNR + 1;
}

html:

<form id="form">
    <input style="width: 500px;" type="add" id="plusButton" onclick="addOne();" />
</form>

current amount <span id="nativeNR"></span>
2
  • You need to set the span to show the value, in addOne() try putting document.getElementById("nativeNR").innerHTML = nativeNR; Commented Mar 17, 2015 at 21:36
  • possible duplicate of setting content between div tags using javascript Commented Mar 17, 2015 at 21:37

3 Answers 3

2

In your case the number will increase by one every time you click. However you are not displaying it in the span. So to do that you can reference the element and set the nativeNR to it.

Your method should be like this

var nativeNR = 1;

function addOne() {
  nativeNR = nativeNR + 1;
  document.getElementById("nativeNR").innerHTML = nativeNR;
}

<form id="form">
    <input style="width: 500px;" type="button" id="plusButton" onclick="addOne();" />
</form>

Also there is not input type="add" it should be type="button"

var nativeNR = 1;
document.getElementById("nativeNR").innerHTML = nativeNR

function addOne() {
    nativeNR = nativeNR + 1;
    document.getElementById("nativeNR").innerHTML = nativeNR;
}
<form id="form">
    <input style="width: 500px;" type="button" id="plusButton" value="add" onclick="addOne();" />
</form>

current amount <span id="nativeNR"></span>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, the add function works and the counting also works. But if the button hasn't been clicked and it is at default number which is 1, it doesn't show the number? jsfiddle.net/9bfvaspj/16
0

You have to use javascript to actually put that number into the DOM. Also, make sure that the function addOne isn't in an onload wrapper; it needs to be in the DOM itself, and declared before the input element that calls it.

The function would look like this:

var nativeNR = 1;

function addOne() {
    nativeNR = nativeNR + 1;
    document.getElementById('nativeNR').innerHTML = nativeNR;
}

Here's a JSFiddle

Comments

0

You will need to write the number to the span as well, now you are simply adding it to the variable in memory:

document.getElementById('nativeNR').innerHTML = nativeNR;

Also, you might want to change the input type to "button".

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.