76

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Phil
  • 2,396
  • 2
  • 18
  • 15

11 Answers11

229

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');
    });
});  
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I get the error Uncaught TypeError: Property 'submit' of object # is not a function but to cancel the cklicks on the links is a very good idea – Phil Apr 10 '14 at 08: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 Apr 10 '14 at 09:07
  • But when you submit the form using jQuery, the button the user clicked is never posted - you have Anlegen and Bnlegen? – mplungjan Apr 10 '14 at 09: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 Apr 10 '14 at 09: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 Apr 10 '14 at 11:22
  • Okay I am so stupid... I think I chose the wrong way to handel the problem because my idee was that the form is normal submitted after the dialog – Phil Apr 10 '14 at 11:26
  • I however fixed it with the second example – mplungjan Apr 10 '14 at 12:07
  • Thank you very very much!!! I changes your code a little bit and now it is perfect. They way I want that it work. Thanks!!!! – Phil Apr 10 '14 at 13:02
  • You say not to NAME anything as 'submit', but I think you should also include that no element should have an ID as 'submit'. Your solution brought me most of the way towards my solution, but I still struggled to figure out I had to change my id. – twinlakes Jan 17 '15 at 22:21
  • 30
    "The NUMBER ONE error is to have ANYTHING with ID or NAME "submit" in your form." Superb comment, thank you. – draconis Jan 29 '15 at 12:11
  • 6
    "The NUMBER ONE error is to have ANYTHING with ID or NAME "submit" in your form." - life saver! – ITD Dec 01 '17 at 10:04
  • My form was not submitting and I was trying to figure out the problem. So far, everything was good in my perspective, however finally I found that using a line of JS code document.getElementById("form_id").submit(); or $("#form_id")[0].submit(); working, my form wasn't submitting without this JS code, do you know anybody why? I don't want to use any JS code to submit my form as I really don't need that. Thanks in advance for your help. – Elias Hossain Mar 02 '19 at 03:14
  • @ITD is correct, i had a with the name="submit" even though the Id was "saveButton" and it was preventing my form from submitting – mknopf May 22 '19 at 13:45
  • `The NUMBER ONE error is having ANYTHING with submit as ID or NAME in your form.` This may not be true. E.g. WordPress WooCommerce used `` in both HTML form and PHP side validation. It is not a good method to just erase it. For plugin developers, better to figure out one way to operate the form without removing that submit button. – harrrrrrry Nov 29 '19 at 22:44
  • Please see my updated answer. Using `login` as name or id is not a problem – mplungjan Nov 30 '19 at 05:16
  • I had `type="button"` instead of `type="submit"` – joshlsullivan Apr 28 '21 at 01:41
  • 2
    The NUMBER ONE error is having ANYTHING with submit as ID or NAME in your form. This was true in my case and it saved my life. Thanks~~~ – Afifa Apr 20 '22 at 09:05
67

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

Kannan K
  • 4,411
  • 1
  • 11
  • 25
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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().
Barmar
  • 741,623
  • 53
  • 500
  • 612
BrownEyes
  • 2,257
  • 18
  • 20
  • The submit event I trigger that way is than the same the form would trigger without my extra code? – Phil Apr 10 '14 at 11:21
4

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')); 
Ben
  • 143
  • 1
  • 8
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.

Ali Rasouli
  • 1,705
  • 18
  • 25
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.

  • Dont validate anything using JS, unless its backend. – nikksan Oct 02 '17 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 Apr 19 '20 at 12:40
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.)

DevBodin
  • 163
  • 7
  • 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: 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
    , 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 Apr 19 '20 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 Apr 21 '20 at 22:29
1

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

Antony
  • 3,875
  • 30
  • 32
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/

gornvix
  • 3,154
  • 6
  • 35
  • 74
1

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

<form>
  <form></form>
</form>
Maris Mols
  • 334
  • 1
  • 2
  • 10
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.