gpt4 book ai didi

jQuery 动态表单验证

转载 作者:行者123 更新时间:2023-12-01 00:21:54 25 4
gpt4 key购买 nike

工作 js fiddle :http://jsfiddle.net/dofpezeg/这是一个动态表单,我必须在其中应用验证。我面临的问题是,当我单击“添加”按钮时,会创建新字段,并且验证不会自动在它们上运行。我通过“:input.req”使用了每个循环,其中req 是我为所有元素指定的类名,无论是静态元素还是新创建的元素。现在,在 onclick 中,我使用 this.val() 来检查不适用于新创建的字段的空白空间。当我打印“input.req.val()”中存储的值时,它总是选取第一个字段的值通过循环,我如何以某种方式应用验证,以便新字段不仅对空字段而且对正则表达式也有效

      $(document).on('click', '#btnac', function() {
var empty = false;
$(':input.req').each(function() {
console.log($(':input.req').val());
var cbn = $('.newcbn').val();
var cba = $('.newcba').val();
var cban = $('.newcban').val();
var cbic = $('.newcbic').val();
var cuser = $('#cuser').val();
alert($(':input.req').val());

if ($(this).val() === '') {
empty = true;
} else if (/^[a-zA-Z ]+$/.test(cbn) === false) {
empty = true;
} else if (/^[a-zA-Z ]+$/.test(cba) === false) {
empty = true;
} else if (/^[0-9]+$/.test(cban) === false) {
empty = true;
} else if (/^[A-Za-z]{4}\d{7}$/.test(cbic) === false) {
empty = true;
} else if (/^[0-9]+$/.test(cuser) === false) {
empty = true;
} else {
empty = false;
}

});
if (empty) {
$('#btnac').attr('disabled', 'disabled');

} else {
$('#btnac').removeAttr('disabled');
}

});

最佳答案

尝试下面的代码,希望这是您想要的。

   $(document).on('click', '#btnac', function() {
var empty = false;
$(':input.req').each(function() {
var val = $(this).val();// the value of the input on current loop index
var $this = $(this);

if (val === '') {// if value is empty
empty = true;
} else if ($this.hasClass('newcbn')) {// test use different Regexp according to the form input's class
empty = !/^[a-zA-Z ]+$/.test(val);
} else if ($this.hasClass('newcba')) {
empty = !/^[a-zA-Z ]+$/.test(val);
} else if ($this.hasClass('newcban')) {
empty = !/^[0-9]+$/.test(val);
} else if ($this.hasClass('newcbic')) {
console.info(val)
empty = !/^[A-Za-z]{4}\d{7}$/.test(val);
} else if ($this.attr('id') === 'cuser') {// test form $('#cuser')
empty = !/^[0-9]+$/.test(val);
} else {
empty = false;
}

if (empty) {// if value didn't pass validate, break loop and disable button #btnac
return false;
}

});

if (empty) {
$('#btnac').attr('disabled', 'disabled');

} else {
$('#btnac').removeAttr('disabled');
}

});

我使用输入的类来确定要测试哪个正则表达式值,如果任何值错误,它只会破坏 $(':input.req').each()循环,然后禁用该按钮。

关于jQuery 动态表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45790843/

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