prevent form submission (javascript)
Asked Answered
S

3

8

I have a form with a text input:

<form name="form1">
    <cfinput type="text" name="text1" id="text1" onChange="someFunc();">
</form>

I only want it to submit in certain cases. (I run some error-checking first)

<script>
function someFunc() {
    if (1==2) {
    document.form1.submit();
} else {
            alert("Not submitting");
    }
</script>

The problem is: even though the alert is triggering fine, somehow, the form is still submitting (There are no other submit statements aside from the one!).

Many thanks if anyone can shed some light on this . . .

Spock answered 16/6, 2014 at 16:52 Comment(2)
Digital Chris's suggestion will work, but it's not "best practice". Look at jQuery's event.preventDafault() method if you go this route and have your script submit the form when validation returns true. But I still suggest looking at my answer below.Gusgusba
Many thanks for your helpful suggestions. 1. I can't see Digital Chris' response. 2. I tried using preventDefault() but it didn't work. 3. Why is the "Default" for the text input set to submitting the form? The OnChange() attribute (the only action attribute specified) is pointing to my someFunc() function, which doesn't call document.form1.submit(), so WHERE IN THE WORLD is the code getting the idea that the form should submit? Many thanks in advance for clarifying!Spock
B
22

There's a fundamental flaw with this approach. You are currently telling the form that when text1 changes, then call someFunc(). If true, use JavaScript to submit the form. If false, go on about your business. If you hit enter in the text input, the form still submits. If there is a submit button that gets clicked, the form still submits.

The basic way to approach this is like so:

<form name="form1" onsubmit="return someFunc()">
    <input type="text" name="text1" id="text1">
</form>

When the from is submitted, call someFunc(). This function must return either true or false. If it returns true, the form submits. If false, the form does nothing.

Now your JavaScript needs a slight alteration:

<script>
function someFunc() {
    if (1==2) {
        return true;
    } else {
        alert("Not submitting");
        return false;
    }
}
</script>

You can still have other functions called when a field is changed, but they still won't manage the form's final submission. In fact, someFunc() could call the other functions to do a final check before returning true or false to the onsubmit event.

EDIT: Documentation on implicit form submission.

EDIT 2:

This code:

$(document).ready(function(){ 
    $("#text1").on('change', function(event){ 
        event.preventDefault(); 
    }); 
});

is stopping the default processing for the change event associated with that element. If you want to affect the submit event, then you'd do this:

$(document).ready(function(){ 
    $("#form1").submit(function(event){ 
        event.preventDefault(); 
    }); 
});

Which would allow you to do something like this:

$(document).ready(function(){ 
    $("#form1").submit(function(event){ 
        if ( $('#text1').val() !== "foo" ) {
            alert("Error");
            event.preventDefault(); 
        }
    }); 
});
Bolinger answered 16/6, 2014 at 17:55 Comment(9)
Many thanks for your reply. However, I still have a few questions: 1. why does the form submit just because I hit enter in the text input? Shouldn't it only submit if a document.form1.submit() command is executed? 2. I don't see a fundamental flaw in the approach as isn't it perfectly valid not to have a submit button? I don't want a submit button. I only want to submit when the text-box changes, and only then when the text is valid. Many thanks for your feedback!Spock
A form doesn't need a submit button. Most browsers submit forms when you press enter inside an input. Take this comment form for example: when I'm finished typing, I can click "Add Comment" or just hit the Enter key and the form submits. It's possible to catch the event of the Event key being pressed and stop that from submitting the form, but it's not often used as it can interfere with a user's workflow. It's when the form is submitted that the submit event, which can be defined in the form tag using the "onsubmit" attribute, gets fired.Bolinger
Many thanks. That's helpful, but where is the form getting the idea that it should submit just because the Enter key is entered? I didn't specify that. I only specified that onChange() should point to someFunc(). If I didn't have an onChange() attribute, then the form wouldn't think about submitting just because I hit Enter in a text input. Do you mean that any time you have an onChange() attribute, Coldfusion (or Javascript) will automatically tack on a submit?Spock
This has nothing to do with ColdFusion, this is core HTML functionality. onChange only fires once the cursor leaves that particular input and that input's value has changed. Pressing enter in any text input automatically fires a form submission in all major browsers. I've added a link to the HTML spec, specifically to do with form submission, to my answer.Bolinger
Got it. That's very helpful. Any ideas why the following is not working?: $(document).ready(function(){ $("#text1").onchange(function(event){ event.preventDefault(); }); });Spock
See Edit 2 in my answer.Bolinger
Many thanks again. Also very helpful, but to test it out, I tried to stop the change event with my original code, and it's just not firing. I tried change, onchange, keypress, keydown. I made sure to include the jquery link at the top of the document, but the jquery event handler is just not working at all. Any ideas? Tks!Spock
Sorry, the code you have is ".onchange". That's not the correct syntax. It's either ".on('change', function(event)" or ".change(function(event)". I've fixed my example.Bolinger
Many thanks. I've tried those too, but no luck either. I'll re-post to start a new thread with topic of preventDefault(). All you help much appreciated!Spock
H
2
 var form = document.getElementById("Your Form ID");

 form.addEventListener("submit", function (e) {
      if ("Your Desired Conditions.") {
          e.preventDefault();
      }
 });
Hartsfield answered 21/10, 2015 at 17:13 Comment(0)
D
1

use the following code it will work perfectly fine

<form onsubmit="return false;" >
Daystar answered 5/12, 2016 at 7:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.