Paranoid Android
Paranoid Android

Reputation: 5037

Javascript alert

I use alert boxes to warn the user about errors when submitting a form on a website I am working on, but each time I click the "ok" button to close the alert box, the page go back to the top and I need to scroll down again to see the form.

I checked other website but this does not happen despite the code is pretty much the same. What is wrong?

Upvotes: 0

Views: 333

Answers (2)

nickf
nickf

Reputation: 546433

The page jumping to the top is usually a sign that you are linking to '#' but not cancelling the action - I've never seen that happen on a form submit myself.

Here's an example of something which might cause the page to jump:

// HTML
<a href="#" onclick="return doSomething()">

// JS
function doSomething() {
    blah();
    x = 5 / 0;      // divide by zero error, therefore the next line
    return false;   // is not executed
}

After the page jumps, look in the address bar. Is there a # at the end?

Just make sure that onclick or onsubmit functions always return false if you don't want the default action to occur.

Upvotes: 1

Noon Silk
Noon Silk

Reputation: 55172

I suspect you're letting the form submit still, you should have something like:

<form onsubmit='return checkThings();'>


function checkThings ()
{
    if( somethingBad ){
        return false;
    }

    return true;
}

Returning false will stop the form from submitting.

Upvotes: 0

Related Questions