79

I have that form

<form action="deletprofil.php" id="form_id" method="post">
            <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
                <button type="submit" name="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
                <button type="submit" name="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
            </div>
        </form> 

and that Popup from jQuery Mobile

<div class="ui-popup-container pop in ui-popup-active" id="popupDialog-popup" tabindex="0" style="max-width: 1570px; top: 2239.5px; left: 599px;">
    <div data-role="popup" id="popupDialog" data-overlay-theme="b" data-theme="b" data-dismissible="false" style="max-width:400px;" class="ui-popup ui-body-b ui-overlay-shadow ui-corner-all">
        <div data-role="header" data-theme="a" role="banner" class="ui-header ui-bar-a">
            <h1 class="ui-title" role="heading" aria-level="1">Delete Page?</h1>
        </div>
        <div role="main" class="ui-content">
            <h3 class="ui-title">Sicher dass Sie das Profil löschen wollen?</h3>
            <p>Es kann nicht mehr rückgängig gemacht werden.</p>
            <a href="#" id="NOlink" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b">Abbrechen</a>
            <a href="#" id="OKlink" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b">OK</a>
        </div>
    </div>
  </div>

with my jQuery Code

<script language="javascript" type="text/javascript">
$(function(){
    $('#form_id').bind('submit', function(evt){
        $form = this;
        evt.preventDefault();
        $("#popupDialog").popup('open');
        $("#NOlink").bind( "click", function() {
            $("#popupDialog").popup('close');
        });
        $("#OKlink").bind( "click", function() {              
            $("#popupDialog").popup('close');   
            $( "#form_id" ).submit();         
        });         
    });
});    
    </script>

The popup shows up but the form submit does not work. Does someone have any ideas?

5

11 Answers 11

235

The NUMBER ONE error is having ANYTHING with the reserved word submit as ID or NAME in your form.

If you plan to call .submit() on the form AND the form has submit as id or name on any form element, then you need to rename that form element, since the form’s submit method/handler is shadowed by the name/id attribute.


Several other things:

As mentioned, you need to submit the form using a simpler event than the jQuery one

BUT you also need to cancel the clicks on the links

Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click.

<form action="deletprofil.php" id="form_id" method="post">
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });

    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});    

Judging from your comments, I think you really want to do this:

<form action="deletprofil.php" id="form_id" method="post">
  <input type="hidden" id="whichdelete" name="whichdelete" value="" />
  <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
  <button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
  <button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
  </div>
</form> 

 $(function(){
    $("#NOlink, #OKlink").on("click", function(e) {
        e.preventDefault(); // cancel default action
        $("#popupDialog").popup('close');
        if (this.id=="OKlink") { 
          // trigger the submit event, not the event handler
          document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
        }
    });
    $(".delete").on("click", function(e) {
        $("#whichdelete").val(this.value);
    });
    $('#form_id').on('submit', function(e){
      e.preventDefault();
      $("#popupDialog").popup('open');
    });
});  
8
  • I get the error Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function but to cancel the cklicks on the links is a very good idea
    – Phil
    Commented Apr 10, 2014 at 8:55
  • The buttons will be generated from a Database (User represented as button) and wenn you click on them I hava $_Post['buttoname] to delet them with php
    – Phil
    Commented Apr 10, 2014 at 9:07
  • But when you submit the form using jQuery, the button the user clicked is never posted - you have Anlegen and Bnlegen?
    – mplungjan
    Commented Apr 10, 2014 at 9:08
  • Anlegen and Anlegen will be then created out of the database and the Value = will be userid so when you click on it that I can delet the user with php
    – Phil
    Commented Apr 10, 2014 at 9:18
  • No you cannot because you cancel the form submission and submit the form with jQuery!!! SO you need to capture the click in a hidden field or you witl NOT see which button was clicked
    – mplungjan
    Commented Apr 10, 2014 at 11:22
69

Because when you call $( "#form_id" ).submit(); it triggers the external submit handler which prevents the default action, instead use

$( "#form_id" )[0].submit();       

or

$form.submit();//declare `$form as a local variable by using var $form = this;

When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element

7
  • or $form.submit() since $form = this; inside the scoope of $('#form_id').bind('submit'..
    – Stphane
    Commented Apr 10, 2014 at 8:37
  • @f00bar yes... just updated... was wary about it because it was declared as a global variable Commented Apr 10, 2014 at 8:38
  • 1
    I tryey it but I get the error: Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function
    – Phil
    Commented Apr 10, 2014 at 8:49
  • 3
    @Phil rename the buttons... don' use name="submit" in a form element Commented Apr 10, 2014 at 8:51
  • 1
    @Phil I think you can just remove the name attribute from the buttons Commented Apr 10, 2014 at 8:53
8

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

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.

So basically, .submit is a binding function, to submit the form you can use simple Javascript:

document.formName.submit().
1
  • The submit event I trigger that way is than the same the form would trigger without my extra code?
    – Phil
    Commented Apr 10, 2014 at 11:21
5

Since every control element gets referenced with its name on the form element (see forms specs), controls with name "submit" will override the build-in submit function.

Which leads to the error mentioned in comments above:

Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

As in the accepted answer above the simplest solution would be to change the name of that control element.

However another solution could be to use dispatchEvent method on form element:

$("#form_id")[0].dispatchEvent(new Event('submit')); 
1

if there is one error in the the submit function,the submit function will be execute. in other sentences prevent default(or return false) does not work when one error exist in submit function.

1
  • unless the preventDefault is the first statement in the handler
    – mplungjan
    Commented May 13, 2017 at 6:32
1

If you are doing form validation such as

type="submit" onsubmit="return validateForm(this)"

validateForm = function(form) {
if ($('input#company').val() === "" || $('input#company').val() === "Company")  {
        $('input#company').val("Company").css('color','red'); finalReturn = false; 
        $('input#company').on('mouseover',(function() { 
            $('input#company').val("").css('color','black'); 
            $('input#company').off('mouseover');
            finalReturn = true; 
        }));
    } 

    return finalReturn; 
}

Double check you are returning true. This seems simple but I had

var finalReturn = false;

When the form was correct it was not being corrected by validateForm and so not being submitted as finalReturn was still initialized to false instead of true. By the way, above code works nicely with address, city, state and so on.

2
  • Dont validate anything using JS, unless its backend.
    – nikksan
    Commented Oct 2, 2017 at 11:54
  • I know this is old, although you should validate your forms using the browsers in built form validation, not manually with hand written JS. i.e. You want to attach to the submit event (which you've got) but using the required attributes and input types for data validation (input type="email", input type="text", etc.)... The actual data should be validated server side before use.
    – AdheneManx
    Commented Apr 19, 2020 at 12:40
1

Don't forget to close your form with a </form>. That stopped submit() working for me.

1

Alright, this doesn't apply to the OP's exact situation, but for anyone like myself who comes here facing a similar issue, figure I should throw this out there-- maybe save a headache or two.

If you're using an non-standard "button" to ensure the submit event isn't called:

<form>
  <input type="hidden" name="hide" value="1">
  <a href="#" onclick="submitWithChecked(this.form)">Hide Selected</a>
 </form>

Then, when you try to access this.form in the script, it's going to come up undefined. As I discovered, apparently anchor elements don't have same access to a parent form element the way your standard form elements do.

In such cases, (again, assuming you are intentionally avoiding the submit event for the time-being), you can use a button with type="button"

<form>
  <input type="hidden" name="hide" value="1">
  <button type="button" onclick="submitWithChecked(this.form)">Hide Selected</a>
 </form>

(Addendum 2020: All these years later, I think the more important lesson to take away from this is to check your input. If my function had bothered to check that the argument it received was actually a form element, the problem would have been much easier to catch.)

2
  • <button type="submit"></button> Is the correct syntax for a button when used to submit a form, although in the context you've got it it's really not different from: <input type="submit" value="Hide selected" /> You should also attach JS code for forms to the submit event, not the button / link; and rely on the browser to verify form data with the type attribute. So you'd put the JS on the form with <form onSubmit="submitWithChecked(this)">, as opposed to on the button... and you shouldn't need JS to validate your form for a simple form submission. Hope this is helpful :-)
    – AdheneManx
    Commented Apr 19, 2020 at 12:45
  • @AdheneManx As you could have inferred from my use of an anchor tag in the first code block, this was not a traditional form. The onclick function dynamically generates hidden inputs and appends them to the form element prior to submission. Attaching an onSubmit attribute would have needlessly necessitated (a) adding an event.preventDefault(); and (b) working around the circular logic in which the function calls submit(), which calls the function, which calls submit().
    – DevBodin
    Commented Apr 21, 2020 at 22:29
1

You can use jQuery like this:

$(function() {
    $("#form").submit(function(event) {
        // do some validation, for example:
        username = $("#username").val();
        if (username.length >= 8)
            return; // valid
        event.preventDefault(); // invalidates the form
    });
});

In your HTML:

<form id="form" method="post">
    <input type="text" name="username" required id="username">
    <button type="submit">Submit</button>
</form>

References:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event https://api.jquery.com/submit/

1

My problem was that I had one form within another form.

<form>
  <form></form>
</form>
0

Some time you have to give all the form element into a same div.

example:-

If you are using ajax submit with modal.

So all the elements are in modal body.

Some time we put submit button in modal footer.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.