gpt4 book ai didi

javascript - jQuery:按钮仅在单击两次后才提交表单

转载 作者:行者123 更新时间:2023-11-30 15:48:17 24 4
gpt4 key购买 nike

我正在制作一个表单验证功能,如果没有空输入按钮需要点击两次才能正常工作。

这是我的功能:

function validate(root, animation, error) {
$('.button').on('click', function(event) {
event.preventDefault()

var isEmpty = false,
root = $(root),
animation = animation ? animation : 'animation animation-shake',
error = error ? error : 'error';

root.find('form').find('.required').each(function() {
if ($(this).val().length == 0) {
isEmpty = true;
root.addClass(animation);
$('.required.error:first').focus();
$(this).addClass(error).on('keydown', function() {
$(this).removeClass(error);
root.removeClass(animation);
});
}
});

if (isEmpty) return;
$(this).unbind('click');
});
}

调用函数的代码:

validate('#login-box .box');

任何想法都会很棒,还有关于如何缩短/改进代码的建议。

最佳答案

你的方法应该是:

function validate(root, animation, error) {
$('.button').on('click', function(event) {
/* event.preventDefault();*/ //<< remove it
var isEmpty = false,
/*...*/
/*if (isEmpty) return;
$(this).unbind('click');*/ //<< remove it

// and set at handler bottom
if (isEmpty) event.preventDefault();
});
}

仅在需要时阻止提交行为。

关于javascript - jQuery:按钮仅在单击两次后才提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com