最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Call a JavaScript function before an action in an HTML form - Stack Overflow

programmeradmin4浏览0评论

Can I intercept a form submit action and do some JavaScript function before sending it to POST or GET?

For example:

<form action="something.php" method="post">
     <input type="text" value="Some data"/>
     <input ... ... ... />
     <input type="submit" value="Send"/>

</form>

Is there a way I can call a JavaScript function before calling action when I click the submit button?

javascriptFunction();
// Now go to form action...

Can I intercept a form submit action and do some JavaScript function before sending it to POST or GET?

For example:

<form action="something.php" method="post">
     <input type="text" value="Some data"/>
     <input ... ... ... />
     <input type="submit" value="Send"/>

</form>

Is there a way I can call a JavaScript function before calling action when I click the submit button?

javascriptFunction();
// Now go to form action...
Share Improve this question edited Jul 20, 2023 at 18:18 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Nov 21, 2016 at 0:25 Fuczi FucziFuczi Fuczi 4152 gold badges5 silver badges13 bronze badges 3
  • 3 The onSubmit event is what you're looking for. – Steve G Commented Nov 21, 2016 at 0:27
  • Possible duplicate of stackoverflow./q/5897360/2182349 – user2182349 Commented Nov 21, 2016 at 0:33
  • 3 Possible duplicate of before form submit call function javascript – K Scandrett Commented Nov 21, 2016 at 0:56
Add a ment  | 

2 Answers 2

Reset to default 11
<form action="something.php" method="post" onsubmit="return myFunction()">
     <input type="text" value="Some data"/>
     <input ... ... ... />
     <input type="submit" value="Send"/>
</form>

<script type="text/javascript">
    function myFunction() {

        // Do something here

        // If you want to submit form
        return true;

        // If you don't want to submit
        return false;
    }
</script>

Try to add an onclick event to the button

onclick="yourfunction()"

and submit the form at the end of the function

document.getElementById("yourform").submit()
发布评论

评论列表(0)

  1. 暂无评论