[英]Prevent Elementor form submission with jQuery
We have a simple Elementor form with one field for an email address and a submit button, for people to sign up to a newsletter.我们有一个简单的 Elementor 表单,其中一个字段用于 email 地址和一个提交按钮,供人们注册时事通讯。
I'm trying to add some custom validation to only allow submissions from .co.uk
, .gov.uk
, and gmail.com
email addresses, and prevent submission if the input doesn't match one of those.我正在尝试添加一些自定义验证,以仅允许来自.co.uk
、 .gov.uk
和gmail.com
email 的提交地址与其中一个地址匹配,并阻止提交。
The validation itself works, in the sense that it displays the custom error message when appropriate, but it's not preventing submissions despite calling e.preventDefault()
, e.stopPropagation();
验证本身有效,因为它在适当时显示自定义错误消息,但尽管调用e.preventDefault()
和e.stopPropagation();
但它并没有阻止提交。 , and return false;
,并return false;
. .
Every thread I've looked at says this should work in theory but perhaps it's different with Elementor forms?我看过的每个线程都说这在理论上应该有效,但也许它与 Elementor forms 不同? Any ideas?有任何想法吗?
(function($) {
$(document).ready(function() {
const accepted = ['.co.uk', '.gov.uk', 'gmail.com'],
form = $('#mail_signup');
$(form).submit(function(e) {
$('.mail-form-invalid').remove();
const email = $('#form-field-email').val(),
valid = accepted.some(accepted => email.includes(accepted));
if (!valid) {
e.preventDefault();
e.stopPropagation();
$(form).after('<p class="mail-form-invalid" style="color: #f00;">Sorry, we only allow submissions from .co.uk, .gov.uk and gmail.com.</p>');
return false;
}
});
});
})(jQuery);
Thanks to Rory McCrossan's comment I was able to update my code to listen for the submit button click instead:感谢 Rory McCrossan 的评论,我能够更新我的代码来监听提交按钮的点击:
<script>
(function($){
$(document).ready(function(){
const accepted = ['.co.uk','.gov.uk','gmail.com'],
form = $('#mail_signup'),
input = $('#form-field-email'),
submit = $(form).find('button[type="submit"]');
function validate(e){
$('.mail-form-invalid').remove();
const email = $(input).val(),
valid = accepted.some( accepted => email.includes( accepted ) );
if (!valid) {
e.preventDefault();
e.stopPropagation();
$(form).after('<p class="mail-form-invalid" style="color: #f00; margin-top: 10px;">Sorry, we only allow submissions from .co.uk, .gov.uk and gmail.com.</p>');
return false;
}
}
$(submit).on('click',function(e){
validate(e);
});
});
})(jQuery);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.