0

I've got a piece of javascript that validates the entries in a form. It looks like this:

    function testSubmit() {
        var x = document.forms["myForm"]["input1"];
        if (x.value == "") {
            alert('Not allowed!!');
            return false;
        }
        return true;
    }

    function submitForm() {
        if (testSubmit()) {
            document.forms["myForm"].submit();
            document.forms["myForm"].reset();
        }
    }

I'm using a button with onclick="submitForm()" to call it, however when I use a button tag, it seems to just go through the whole check and do the form action which is post. If I use a input tag with type="button", that works like expected. Is there a difference in how this works between the 2 tags? Here's a codepen showing the problem: http://codepen.io/anon/pen/OyVGQQ

The button on right works gives you a pop and let's you return to the form. The button on the left gives you a pop-up, but then tries to post the form anyway.

Wandel
  • 15
  • 3
  • 2
    tag `button` by default to submit on click – Grundy Sep 09 '15 at 13:43
  • For form validation, don't attach an onclick event to the submit button. Attach an onsubmit event to the form. There are other ways to submit the form than clicking on the submit button, like pressing enter in a text field. – JJJ Sep 09 '15 at 13:47

2 Answers2

1

In your pen, you're using <button type="submit" onclick="submitForm()" />. You have to use type="button" if you don't want to submit by default.

chrona
  • 1,853
  • 14
  • 24
  • you can still use the – deebs Sep 09 '15 at 13:49
  • @deebs, but if you do `return false` always why you set type to "submit"? :-) – Grundy Sep 09 '15 at 13:49
  • I guess the type=submit is unneeded, but regardless, you can still use the button tag if you add return false, right? – deebs Sep 09 '15 at 13:54
  • 1
    @Grundy the intended behavior of the button is still to submit the form, it just adds some additional validation. As of that you should keep the semantic information that it is the submit button. – t.niese Sep 09 '15 at 13:59
  • @t.niese, in this case validation function should not do submit, it should just return true or false, something like `` – Grundy Sep 09 '15 at 14:02
  • @Grundy That depends. In this particular case the validation can be done synchronously, but there could also be an ajax based validation taking place. So I don't see a problem in returning false and then do a `.submit()` or using ajax to post the data to the server. The `type="submit"` does not tell how the form should be submitted, it just tells that this action will somehow take place if the button is pressed. – t.niese Sep 09 '15 at 14:06
0

If you need to use the button tag, you can add "return false" after to keep it from submitting by default. http://codepen.io/anon/pen/bVdJOm

<button type="submit" onclick="submitForm(); return false;" />
deebs
  • 1,390
  • 10
  • 23