Muhammad Ali Dildar
Muhammad Ali Dildar

Reputation: 1527

Function call repeating itself

I've just started JavaScript and I am facing a problem. I've written a script in which I am calling a function. I don't know why this script is calling itself twice.

The code is as below:

<html>
<head>

<script type="text/javascript">

var randomNo1 = Math.floor(Math.random()*10);
var randomNo2 = Math.floor(Math.random()*10);

window.onload = ask;

function ask()
{
    alert("How much " + randomNo1 + " times " + randomNo2 + "?");
}

function question()
{
    var product = randomNo1 * randomNo2;
    var stdAnswer = document.getElementById('answer').value;
    
    if(stdAnswer == product)
    {
        alert("Very good!")
        //generate new nos
        randomNo1 = Math.floor(Math.random()*10);
        randomNo2 = Math.floor(Math.random()*10);
        ask();
    }
    else
    {
        alert("No. Please try again.");
        ask();
    }
}
</script>

</head>

<body>
<form>
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>
</body>
</html>

Upvotes: 0

Views: 2556

Answers (6)

Andrew Leach
Andrew Leach

Reputation: 12983

You have a form with a submit button. With no action in the form, it resubmits the page. You can stop this with

<input type="submit" value="Check" onClick="question();return false" />

Upvotes: 0

afaf12
afaf12

Reputation: 5436

Add action="#" to your form, to avoid page being refreshed when form is submitted.

<form action="#">
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>​

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

Because your button is a submit button. When clicked it runs click handlers (if specified), then posts the form. So you call ask() twice. One time in a click handler, and another time in a window.onload handler.

After this form is submitted, page simply reloads (because it has no associated action). And onload handler is fired again.

You can see it here: http://jsbin.com/ukusof.

Upvotes: 1

Daxcode
Daxcode

Reputation: 434

You're submitting the form, which loads the page again, so ask will be fired again on load.

Upvotes: 0

R&#233;mi Breton
R&#233;mi Breton

Reputation: 4269

Your form as no method nor action. When you click your submit button, the page refresh itself, thus firing ask again.

Upvotes: 0

KevinDTimm
KevinDTimm

Reputation: 14376

You call it twice, once at startup window.onload = ask; and once in question

[edit]
note too that you don't have a ; after the first alert() in question()
[/edit]

Upvotes: 1

Related Questions