簡體   English   中英

如何在表單提交上觸發兩個函數?

[英]How to trigger two function on form submit?

表單提交時我有一個表單我將調用一個javascript函數並將其操作以形成處理程序。

<form action="subscribe.php" onsubmit="return form_check(this)" method="post">
<input type="text" value="">
<input type="submit" value="click">
</form>

一切正常,現在我想將相同的表單字段發送到另一個javascript函數,所以我嘗試這樣提交代碼

    <form action="subscribe.php" 
onsubmit="return (form_check(this) & another_script(this))" method="post">

添加 in onsubmit但單擊按鈕時該功能不會觸發。 我認為這是由於表單中的action="subscribe.php"

我想將表單值發送到另一個javascript函數。 我怎么能實現這個目標?

使用jQuery,您可以捕獲表單提交。 當用戶嘗試提交表單時, submit事件將發送到元素。

HTML

<form id="myForm">...</form>

jQuery的

$("#myForm").submit(function(event){
  event.preventDefault();

  var this = something;

  myFunctionA(this);
  myFunctionB(this);
});

var myFunctionA = function(this){
  // Function operation
}

var myFunctionB = function(this){
  // Function operation
}

根據你想要做的事情,有一些答案。

如果你想簡單地運行兩個函數而不返回任何東西,你可以簡單地做:

onsubmit="form_check(this); another_script(this);"

如果要始終運行another_script返回 form_check的值, form_check可以執行以下操作:

onsubmit="another_script(this); return form_check(this);"

如果你想form_check返回true運行another_script (如果form_checkanother_script都返回true則返回true ),你可以這樣做:

onsubmit="return form_check(this) && another_script(this);"

但是,通常不鼓勵在onsubmit處理程序中放入太多代碼。 您應該在使用DOM或jQuery之后綁定事件處理程序。

這有用嗎?

onsubmit="another_script(this); return form_check(this);"

當然,使用不顯眼的事件處理程序總是更好。

onsubmit="return ((form_check(this) + another_script(this))===2);"

演示小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM