javascript - 如何在表单完成之前禁用 Stripe 付款请求按钮?
问题描述
我在与表单相同的页面上设置了 Stripe 的付款请求按钮。表单上有验证。在表单完成之前,我需要能够禁用付款请求按钮,但我无法找到执行此操作的方法。
付款请求按钮设置:
<script src="https://js.stripe.com/v3/"></script>
<div id="payment-request-button">
<!-- A Stripe Element will be inserted here. -->
</div>
<script>
var stripe = Stripe('KEY');
var paymentRequest = stripe.paymentRequest({
country: 'US',
currency: 'usd',
total: {
label: 'Demo total',
amount: 1000,
},
requestPayerName: true,
requestPayerEmail: true,
});
var elements = stripe.elements();
var prButton = elements.create('paymentRequestButton', {
paymentRequest: paymentRequest,
});
// Check the availability of the Payment Request API first.
paymentRequest.canMakePayment().then(function(result) {
if (result) {
prButton.mount('#payment-request-button');
} else {
document.getElementById('payment-request-button').style.display =
'none';
}
});
paymentRequest.on('token', function(ev) {
// Send the token to your server to charge it!
fetch('/charges', {
method: 'POST',
body: JSON.stringify({token: ev.token.id}),
headers: {'content-type': 'application/json'},
})
.then(function(response) {
if (response.ok) {
// Report to the browser that the payment was successful, prompting
// it to close the browser payment interface.
ev.complete('success');
} else {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete('fail');
}
});
});
</script>
解决方案
click
您可以在事件处理程序中为付款请求按钮的事件执行表单验证。
文档
element.on('click', handler)
单击时触发
Element
。此事件仅从paymentRequestButton
元素发出。
handler
当被调用时,它将被传递一个具有以下属性的事件对象:
preventDefault
同步调用该函数可防止显示浏览器的支付界面。这可用于在显示支付界面之前验证表单。
例子
prButton.on('click', function(event) {
if (!myForm.reportValidity()) {
event.preventDefault();
return;
}
});
推荐阅读
- java - 如何使用 websocket 客户端侦听 rest api
- bash - 除非我不调用脚本 X,否则 bash 如何不完成此循环并且只处理 1 个项目?
- php - 如何创建数组的交集类型
- javascript - 使用动态递增值创建加载条
- ruby - 如何在变量和类之间传递块
- javascript - 如何从 JS 中的外部 url 解码多维 JSON?
- java - Spring 配置文件未从 application.properties 读取值
- python - 将文本中的字母添加到字典中而无需标点符号的功能
- mysql - 错误 1005 (HY000) mySql,在小型数据库上
- python-3.x - Python 3 - 使用 concurrent.futures 并行调用 .exe 的多个实例