我在表单中创建了 eway paynow 按钮。
<form action="?" method="POST">
Name: <input type="text" name="customer_name" value="" />
<script src="https://secure.ewaypayments.com/scripts/eCrypt.js"
class="eway-paynow-button"
data-publicapikey="epk-6AEE4269-0010-4415-A327-8064928AEFD0"
data-amount="0"
data-currency="AUD"
data-allowedit="true"
data-resulturl="http://example.com/responseMsg.php">
</script>
</form>
在加载电子支付之前,我需要检查 customer_name 字段是否为空 形式。如果 customer_name 字段为空,则不加载 eway 付款表单。我该怎么做?我可以运行 javascript 来验证此表单吗?
最佳答案
“立即付款”按钮不提供在打开付款表单之前运行函数的 Hook ,目前也不使用事件监听器。这里的解决方案是:
- 捕获原始 onclick 处理程序
- 添加一个新的事件监听器来执行验证,然后在成功时调用原始的 onclick。
为此我坚持使用纯 JS,jQuery 将允许更清晰的实现:-)
另请注意,我已删除 data-resulturl
属性并将 URL 移至表单标记,否则窗口可能只是重定向而不提交。
<form action="http://example.com/responseMsg.php" method="POST">
Name: <input type="text" name="customer_name" value="" />
<script src="https://secure.ewaypayments.com/scripts/eCrypt.js"
class="eway-paynow-button"
data-publicapikey="epk-6AEE4269-0010-4415-A327-8064928AEFD0"
data-amount="10"
data-currency="AUD"
data-allowedit="true"
data-submitform="yes">
</script>
</form>
<script>
window.onload = function() {
// Find the eWAY Pay Now button - note getElementsByClassName is IE9+
var ewayButton = document.getElementsByClassName("eway-button")[0];
// save and remove old onclick
var oldeWAYclick = ewayButton.onclick;
ewayButton.onclick = null;
// Add new listener with validation
ewayButton.addEventListener("click", function(e){
// Stop form from submitting itself
e.preventDefault();
// Example validation
var name = document.forms[0]["customer_name"].value;
if (name == null || name == "") {
alert("Please complete all fields");
return;
}
// Display payment form
oldeWAYclick();
}, false);
};
</script>
关于javascript - 单击 eWAY paynow 按钮时如何验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32647876/