How to submit a form using javascript

2019-07-31 02:30发布

问题:

I'm trying to click on a submit button and submit a form using purely javascript. I have tried:

document.getElementById('sell_form').submit();

and

for(var i=0;i<document.getElementsByName('operation').length;i++){
    if(document.getElementsByName('operation')[i].value=='Sell'){
        document.getElementsByName('operation')[i].submit();
    }
}

but I just can't get it. Can anyone show me how I could do this?

Thanks in advance.

The web code is:

<form id="sell_form" class="ajaxform" action="/member/sell" method="post">
    <div id="result" class="popup"> </div>  //hidden
    <div class="c-box-body">
        <table width="100%" border="0">
        <div style="text-align:center">
            <br>
            <input type="hidden" value="13" name="pair">    //hidden
            <input type="hidden" value="Sell" name="type">  //hidden
            <input type="submit" value="Calculate" name="calculate">
            <input type="submit" value="Sell" name="operation">   //**This is the one I'm trying to click on
            <input type="reset" value="Clear">
        </div>
    </div>
</form>

What makes this difficult is that the web page is not mine (I'm using greasemonkey in firefox which is essentially and onload javascript event)

回答1:

<script type="text/javascript">
  function callSubmit() {      
      document.forms[0].submit();
  }
</script>

<form id="sell_form" class="ajaxform" action="/member/sell" method="post">
    <div id="result" class="popup"> </div>  //hidden`enter code here`
    <div class="c-box-body">
        <table width="100%" border="0">
        <div style="text-align:center">
            <br>
            <input type="hidden" value="13" name="pair">    //hidden
            <input type="hidden" value="Sell" name="type">  //hidden
            <input type="submit" value="Calculate" name="calculate">
            <input type="submit" value="Sell" name="operation" onclick="callSubmit()">
            <input type="reset" value="Clear">
        </div>
    </div>
</form>


回答2:

var form = document.getElementById("sell_form"),
    button = document.getElementById("sell_button");

function submitForm() {
    form.submit();
}

button.addEventListener("click", submitForm, false);

I'm getting the form and the button instances using the DOM. After that, I create a function which submits the form. Finally, I tell the browser to 'listen' to the button element, and when it 'hears' a click on it, it should run the previously created function.



回答3:

I was able to to it with:

var element = document.querySelector('#sell_form input[name="operation"]');  
    if (element) {  
        element.click();
    }