How to submit a form using javascript

2019-07-31 02:49发布

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)

3条回答
Lonely孤独者°
2楼-- · 2019-07-31 02:59
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楼-- · 2019-07-31 03:07

I was able to to it with:

var element = document.querySelector('#sell_form input[name="operation"]');  
    if (element) {  
        element.click();
    }
查看更多
ゆ 、 Hurt°
4楼-- · 2019-07-31 03:14
<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>
查看更多
登录 后发表回答