Garrett Garrett - 2 months ago 14
jQuery Question

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

<form method="post" action="load_statements.php?action=load" id="loadForm"

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
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)"
)) {
} else {
}, "json"

and as you can see, it calls
, but the form is not submitting (ie. the page is not refreshing). why is that?



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 intact to point out where I was off (as at least two people have already downvoted me for). 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.

Make more sense?