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.

2
  • 2
    tag button by default to submit on click Commented Sep 9, 2015 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. Commented Sep 9, 2015 at 13:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

you can still use the <button> tag without submitting by default using "return false". See my answer below.
@deebs, but if you do return false always why you set type to "submit"? :-)
I guess the type=submit is unneeded, but regardless, you can still use the button tag if you add return false, right?
@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, in this case validation function should not do submit, it should just return true or false, something like <button type="submit" onclick="return testSubmit()" />
|
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;" />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.