2

私は次のようなフォームを持っています:

<form method="POST" action="page.html" onsubmit="alert('foo'); // validate();" name="foobar">
...
</form>

および次のようなリンク:

<div onclick="document.foobar.submit();">click me</div>

submit()メソッドをキャプチャしてvalidate関数を呼び出すにはどうすればよいですか?

JsBinの例

4

4 に答える 4

1

HTML自体からメソッドを呼び出すことができます。変更されたjsbin。クリックしてフォームを送信する代わりに、 submitHandlerフォーム参照を呼び出して渡すことができます。

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
  <script type="text/javascript">
    function validate(){

    }

    function submitHandler(form){
      validate();
      alert('foo');

}
    window.onload = function(){
        document.foobar.submit = submitHandler;
    }
</script>

</head>
<body>
    <form method="POST" action="page.html" onsubmit="submitHandler(this);" name="foobar">
      <input type="text" />
    </form>

    <div onclick="document.foobar.submit()">click me</div>
</body>    
</html>
于 2012-10-10T11:12:04.630 に答える
1

IDを使用してフォームを一意に識別します

document.getElementById('formid').onsubmit = function() {
    // You have captured the submit method now do what you need
};

デモ

于 2012-10-10T11:28:09.723 に答える
0

jQuery.submit()ハンドラーを使用できます。

$('form').submit(function(evt) {
  evt.preventDefault();
  alert('Handler for .submit() called.');
  // Validate function returns false or true
});
于 2012-10-10T11:09:15.140 に答える
0

これを試して:

<script type="text/javascript">
function addEventsToHTML(){
    var form = document.getElementById('foobar');
    form.onsubmit = submitHandler;
    function submitHandler(){
        validate();
    }
}
window.onload = addEventsToHTML;
</script>
于 2012-10-10T11:10:42.063 に答える