Wednesday, February 10, 2010

HTML Submit button still submits even when JavaScript returns false

Here's something that's caught me out a couple of times in the past so I'm documenting it to remind myself.

My web page has a submit <input> tag that looks like this:

<input type="submit" value="Create" />

I want to do some client side validation before I POST the page back to the server so I modify it to call my client side JavaScript function by adding the onclick attribute:

<input type="submit" value="Create" onclick="SubmitCreate();" />

The JavaScript does a bit of validation:

function SubmitCreate() {
    var selectedNodes = tree.getSelectedNodes();
    if (selectedNodes.length < 1) {
        alert('Please select at least one node.');
        return false;

The problem is that even though the SubmitCreate() function is returning false this is not preventing the page from being submitted.

The reason, when shown, is obvious. The onclick attribute should return the JavaScript and not just call it.

<input type="submit" value="Create" onclick="return SubmitCreate();" />



  1. Taking blog posts from my code again? :) Call me old school, but I always put onclick="javascript: return method();" I don't know why I need the "javascript" just helps me feel more in touch with the code.

  2. Ahhhh, that's why!!
    I feel so silly! Thanks for that :-)