jQuery: form not submitting with $("#id").submit(), but will submit with a 'submit' button?
Asked Answered
D

9

41
<form method="post" action="load_statements.php?action=load" id="loadForm"
                            enctype="multipart/form-data">

that is my form, which looks fine to me. in that form, i put this button:

<input type="button" name="submit" id="submit" value="Submit" onclick="confirmSubmit()" class="smallGreenButton" />

here is the function it calls:

function confirmSubmit() {
    // get the number of statements that are matched
    $.post(
        "load_statements.php?action=checkForReplace",
        {
            statementType : $("#statementType").val(),
            year : $("#year").val()
        },
        function(data) {
            if(data['alreadyExists']) {
                if( confirm("Statements already exist for " + $("#statementType").html() + " " + $("#year").val() +
                    ". Are you sure you want to load more statements with these settings? (Note: All duplicate files will be replaced)"
                )) {
                    $("#loadForm").submit();
                }
            } else {
                $("#loadForm").submit();
            }
        }, "json"
    );
}

and as you can see, it calls $("#loadForm").submit();, but the form is not submitting (ie. the page is not refreshing). why is that?

thanks!

Daubigny answered 21/7, 2010 at 21:6 Comment(2)
Do you hit a breakpoint if you put it on the submit call?Gintz
yeah, it runs, but doesn't actually submit the form for some reason.Daubigny
K
18

http://api.jquery.com/submit/

The jQuery submit() event adds an event listener to happen when you submit the form. So your code is binding essentially nothing to the submit event. If you want that form to be submitted, you use old-school JavaScript document.formName.submit().


I'm leaving my original answer above intact to point out where I was off. What I meant to say, is that if you have a function like this, it's confusing why you would post the values in an ajax portion and then use jQuery to submit the form. In this case, I would bind the event to the click of the button, and then return true if you want it to return, otherwise, return false, like so:

$('#submit').click( function() {
  // ajax logic to test for what you want
  if (ajaxtrue) { return confirm(whatever); } else { return true;}
});

If this function returns true, then it counts as successful click of the submit button and the normal browser behavior happens. Then you've also separated the logic from the markup in the form of an event handler.

Hopefully this makes more sense.

Kev answered 21/7, 2010 at 21:14 Comment(9)
Thats if you pass a function. If you just call submit(), the default submit action on the form will be fired, so the form will be submitted.Karaite
... supposedly... but for some reason, no =(Daubigny
I've updated the answer to explain what I meant. I was not being very clear, that was my bad.Kev
i need to get ajax data because depending on the form, the confirmation will be different (if you want specifics, i am checking to see if the file a user is uploading is already in the database, and if so, notifying that the old file will be overwritten). although it kills me to say it, your answer is better than mine, as it is more semantic and does not require an invisible submit button. i'm marking this as the correct answer, but i'm still confused as to why the submit() function didn't work =(Daubigny
To be honest I think your problem is that the event that's firing it is the click of the submit button, and you're telling jQuery to perform a submit() within that function. All you really have to do is return true, and the onclick goes through.Kev
Binding the form's submit button makes it impossible to run browser's form validation. Something like <input type="email" required="required" /> will not be checked for being filled out correctly by browser. You may want to have it checked: $("#form-id").submit(function(event) { event.preventDefault(); doSomething(); });. This allows you to do AJAX calls with jQuery and client-side form-validation.Alcoholometer
event.preventDefault(); is for making sure the form is not submitted twice.Alcoholometer
this is not the right answer, it has nothing to do with the actual problem. the real problem is in the submit button's name. When the submit button has the name "submit", that's when jquery gets confused!Redwine
Yeah, see the edit: the below answer makes more sense, this was based on me misunderstanding the question. I've upvoted the below answer but I don't own the question so I can't make it the right one.Kev
D
88

Change button's "submit" name to something else. That causes the problem. See dennisjq's answer at: http://forum.jquery.com/topic/submiting-a-form-programmatically-not-working

See the jQuery submit() documentation:

Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.

Disembodied answered 5/1, 2013 at 19:57 Comment(6)
This seems to be the right answer, not the others. At least it was the exact problem in my case and appears to be the problem in the question. The other answers seem wrong.Prosopopoeia
I tested the same case and found that changing of id or name attributes still produce the same error.Woodcut
This was the answer for me. Took forever to find outBrighten
at first, i thought that it might be the form's id or name that was causing the issue. turns out it was another input element that had an id/name that was submit. Changing that fixed this issue.Koren
Also I found you should also make sure the id of the button element is not set to "submit". The lesson I've learned is NEVER EVER put name="submit" OR id="submit" on a submit button or it will break $("form").submit()! I just spent hours trying to debug a form's behaviour and this was the problem.Archegonium
This is the right answer, i have no idea why the other one is selectedRedwine
V
21

I use $("form")[0].submit()

here $("form") returns an array of DOM elements so by accessing the relevant index we can get the DOM object for the form element and execute the submit() function within that DOM element.

Draw back is if you have several form elements within one html page you have to have an idea about correct order of "form"s

Veratridine answered 27/2, 2013 at 13:57 Comment(2)
Fixed the problem for me, +1Ablative
@garrett $("#loadForm")[0].submit(); works for me. It seems that submit() does not work on an array of elements returned by $("#loadForm") selector.Chancey
K
18

http://api.jquery.com/submit/

The jQuery submit() event adds an event listener to happen when you submit the form. So your code is binding essentially nothing to the submit event. If you want that form to be submitted, you use old-school JavaScript document.formName.submit().


I'm leaving my original answer above intact to point out where I was off. What I meant to say, is that if you have a function like this, it's confusing why you would post the values in an ajax portion and then use jQuery to submit the form. In this case, I would bind the event to the click of the button, and then return true if you want it to return, otherwise, return false, like so:

$('#submit').click( function() {
  // ajax logic to test for what you want
  if (ajaxtrue) { return confirm(whatever); } else { return true;}
});

If this function returns true, then it counts as successful click of the submit button and the normal browser behavior happens. Then you've also separated the logic from the markup in the form of an event handler.

Hopefully this makes more sense.

Kev answered 21/7, 2010 at 21:14 Comment(9)
Thats if you pass a function. If you just call submit(), the default submit action on the form will be fired, so the form will be submitted.Karaite
... supposedly... but for some reason, no =(Daubigny
I've updated the answer to explain what I meant. I was not being very clear, that was my bad.Kev
i need to get ajax data because depending on the form, the confirmation will be different (if you want specifics, i am checking to see if the file a user is uploading is already in the database, and if so, notifying that the old file will be overwritten). although it kills me to say it, your answer is better than mine, as it is more semantic and does not require an invisible submit button. i'm marking this as the correct answer, but i'm still confused as to why the submit() function didn't work =(Daubigny
To be honest I think your problem is that the event that's firing it is the click of the submit button, and you're telling jQuery to perform a submit() within that function. All you really have to do is return true, and the onclick goes through.Kev
Binding the form's submit button makes it impossible to run browser's form validation. Something like <input type="email" required="required" /> will not be checked for being filled out correctly by browser. You may want to have it checked: $("#form-id").submit(function(event) { event.preventDefault(); doSomething(); });. This allows you to do AJAX calls with jQuery and client-side form-validation.Alcoholometer
event.preventDefault(); is for making sure the form is not submitted twice.Alcoholometer
this is not the right answer, it has nothing to do with the actual problem. the real problem is in the submit button's name. When the submit button has the name "submit", that's when jquery gets confused!Redwine
Yeah, see the edit: the below answer makes more sense, this was based on me misunderstanding the question. I've upvoted the below answer but I don't own the question so I can't make it the right one.Kev
A
13

I had a similar problem, took a while to figure it out. jQuery's .submit() function should trigger a form submit if you don't pass a handler to it, but the reason it doesn't is because your submit button is named "submit" and is overriding the submit function of the form.

i.e. jQuery calls the <form>.submit() function of the DOM object, but all inputs within a form can also be access by calling <form>.<inputname>. So if one of your input's is named 'submit' it overrides the <form>.submit() function with <form>.submit - being the input DOM element.... if that makes sense? So when jQuery calls <form>.submit() it doesn't work because submit is no longer a function. So, if you change the name of your button it should work.

Not sure why the console doesn't log an error, perhaps jQuery is first checking that the submit function exists and is just ignoring the request if the function doesn't exist.

Alibi answered 4/12, 2014 at 2:31 Comment(2)
sorry, my post didn't turn out as expected. the second paragraph should read: i.e. jQuery calls the form.submit() function of the DOM object, but all inputs within a form can also be access by calling form.inputname. So if one of your input's is named 'submit' it overrides the form.submit() function with form.submit - being the input DOM element.... if that makes sense? So when jQuery calls form.submit() it doesn't work because submit is no longer a function.Alibi
today i face same problem and your solution worked for me +10 from my side. thanks.Sidecar
D
4

i added an invisible submit button to the form, and instead of calling the submit() function, i call the click() function on the submit button =)

the button: <div style="display:none"><input id="alternateSubmit" type="submit" /></div>

the crazy way to get around the form submission: $("#alternateSubmit").click();

Daubigny answered 22/7, 2010 at 12:49 Comment(1)
I updated my answer to include a new possible solution, which I successfully tested, I can provide the code for that if you'd like it.Kev
E
4

erase attribute "name" in your submit button :

this is your code :

<input type="button" name="submit" id="submit" value="Submit" onclick="confirmSubmit()" class="smallGreenButton" />

should be like this :

<input type="button" id="submit" value="Submit" onclick="confirmSubmit()" class="smallGreenButton" />
Eccles answered 7/9, 2016 at 10:40 Comment(1)
It also works if you change its name from "submit" to something elseSchedule
Q
0

Try this, worked for me

if you do have submit as id or name, you need to rename that form element.

can not give id="submit" to any other element of form if you want to use element.submit() in script.

Form Submit jQuery does not work

Quay answered 27/4, 2020 at 13:50 Comment(0)
P
-1

Looks like you have the submit happening in a callback that only runs after an ajax post in your onclick handler.

In other words, when you click submit, the browser has to first go out and hit the checkForReplace action.

Posada answered 21/7, 2010 at 21:11 Comment(1)
yes, which it does, and then hits $("#loadForm").submit(); which does nothing.Daubigny
T
-3

its Ajax call, why you need to submit your form while you already process it using ajax. You can navigate away from page using

window.location.href = "/somewhere/else";
Tremain answered 21/7, 2010 at 21:12 Comment(1)
i need to process part of it before in order to give the user the correct confirm() statement.Daubigny

© 2022 - 2024 — McMap. All rights reserved.