How to reliably submit an HTML form with JavaScript?

后端 未结 7 1583
面向向阳花
面向向阳花 2020-12-13 20:33

Is there a way to submit an HTML form using JavaScript that is guaranteed to work in all situations?

I elaborate. The common approach seems to be:

fo         


        
相关标签:
7条回答
  • 2020-12-13 20:47

    So, is there any other way to submit an HTML form using JavaScript?

    Update: Take the advice of Jerome (elsewhere in this thread). I'll leave this answer up for historical interest, but it isn't as nice or reliable as Jerome's solution.

    The following approach is ugly, but works.

        var x = document.forms.example;
        var f = document.createElement('form');
        f.action = x.action;
        f.method = x.method;
        f.enctype = x.enctype;
        for (var i = 0; i < x.elements.length; i++) {
            var el = x.elements[i];
            if (el.name !== "submit") {
                f.appendChild(el);
            }
        }
        x.parentNode.replaceChild(f,x);
        f.submit();
    
    0 讨论(0)
  • 2020-12-13 20:47

    For a form named submit just calling its buttons click function works for me.

    document.forms[0].submit.click();  //where submit here is just the name of the button/input tied to the form.
    
    0 讨论(0)
  • 2020-12-13 20:54

    Just use onsubmit ...

    <form name="example" id="example" action="/" onsubmit="document.example.submit();">
      <button type="submit" name="submit" onclick="document.example.submit(); return false;">Submit</button>
    </form>
    
    0 讨论(0)
  • 2020-12-13 20:56

    The best idea is to not name a submit button 'submit', but you can get around it-

    function reallysubmitform(n){
     n= n || 0;
     var f= document.forms[n];
     f.onsubmit= function(){
      return true
     };
     var sub= f.elements['submit'];
     if(sub && sub.type== 'submit') sub.click();
     else f.submit();
    }
    

    reallysubmitform()

    0 讨论(0)
  • 2020-12-13 20:59

    Submiting a form using JavaScript cannot by design be safe.

    Your users can browse your web site on their phone, have disabled JavaScript, tweaked the source of your page, or using Lynx.

    In any case, for accessibility purposes, you will need the good old HTML submit button and some input checks on the server side.

    0 讨论(0)
  • 2020-12-13 21:05

    In Firefox

    formElement.constructor
    

    returns "HTMLFormElement". So you can submit the form by using:

    HTMLFormElement.prototype.submit.call(formElement)
    

    You can extend this to other browsers as well:

    formElement.constructor.prototype.submit.call(formElement)
    
    0 讨论(0)
提交回复
热议问题