Ad

Trying To Run Javascript With A Href For Validation

- 1 answer

At the bottom of my webpage, I have a submit button. I've used this code:

<a onClick="myFunction(); return false;" target="_blank" rel="nofollow noreferrer" href="testpage.html">Submit</a>

What I'm trying to do is when my function is called, I'm checking for validation. If it's false, my function raises an alert and the user doesn't leave the current page...which is what I want. When its true though...nothing changes. When it's true I want them to go to the next link.

function myFunction() {
            if (localStorage.length != 3) {
                alert("Missing Values");
            } else {
                break;
            } 
        }

It goes to the next link when I put in break, but now the alert doesn't get called even if it's requirements are met. Moreover, whey does the break in the else block get called even when the if block requirements are met?

Ad

Answer

Well return false cancels the action. So if you do not want to stop the link, you need to remove that.

<a onclick="return myFunction();" target="_blank" rel="nofollow noreferrer" href="testpage.html">Submit</a>

Now return true or false from myFunction

function myFunction() {
    if (localStorage.length != 3) {
        alert("Missing Values");
        return false;
    }
    return true;
} 
Ad
source: stackoverflow.com
Ad