0

im having a problem with an accumulator on Javascript, im new onto this, so could anybody help me with this? i just want an accumulator for right answers this is my script because it just keeps giving me 0 as a result.

<script type="application/javascript">
 var count=0;
function counter(){
    count=count+1;
}
function results(){
alert ("The number of correct answers is "+count)   
}
</script>

and this is the structure for my buttons

<input type="radio" name="p1" value="answ" onsubmit="counter()">

for correct answer

<input type="radio" name="p1" value="answ1">

for other options

1
  • Hello! Don't forget to accept an answer, you even get 2 rep for it! Commented Apr 4, 2014 at 21:13

2 Answers 2

1

The onsubmit event only works for form elements. You're thinking of onclick. However, it's better to have event listeners.

HTML:

<button id="increment">Click Me</button>
The counter is at <span id="counter">0</span>

JS:

var btn = document.querySelector('#increment');
var ctr = document.querySelector('#counter');
var counter = 0;
var increment = function() {
    counter++;
    ctr.textContent = counter;
};

btn.addEventListener('click', increment);

Here's a JSFiddle to play with

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

2 Comments

Im using the "onclick" on my submit button being the code this one : <input type="submit" value="Submit" onclick="results()" then is there anyway i could trigger the counter from the "radio forms"?
@user3496155 I've updated the question with some code. Does that help explain it?
0

onsubmit would not be triggering the counter() function. I dont think onsubmit can be used on a radio button, and even so clicking it would be not triggering the onsubmit, it would trigger the onclick.

Because counter() is never being executed, the count never increases.

Also make sure your order of events is correct so that counter() will always trigger before results() as I can not see where results() is called in your code.

1 Comment

Im sorry i forgot to put that. im calling results in the submit button <input type="submit" value="Submit" onclick="results()"

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.