gpt4 book ai didi

javascript - 如何在 JavaScript 中最少输入两个表单?

转载 作者:行者123 更新时间:2023-11-28 04:17:56 24 4
gpt4 key购买 nike

我有一个包含 3 个文本输入的表单。我需要提交该表格以对必填字段进行验证。我只需要用户完成该表单的两个输入,而不是其中一个,然后提交表单。我该怎么做?我不明白这里的逻辑。

我的代码:

$('#submit-btn').on('click', function(e){
e.preventDefault();
var input1 = $('#input1').val();
var input2 = $('#input2').val();
var input3 = $('#input3').val();
if(input1 == '' || input2 == ''){
alert('you have to complete only 2 fields')
}else{
$('#form').submit();
}
});
<form action='' method='post' id='form'>
<input type='text' value='' name='input1' id='input1'>
<input type='text' value='' name='input2' id='input2'>
<input type='text' value='' name='input3' id='input3'>
<input type='text' value='' id='submit-btn'>
</form>

最佳答案

您可以使用 each 遍历所有输入并检查有多少输入具有值,如下所示。

$('#submit-btn').on('click', function (e) {
e.preventDefault();
var count = 0;
$('input[type=text]').each(function () {
if (this.value != '') count++;
// use this.value.trim() to prevent empty value
});

if (count<2) {
alert('you have to complete only 2 fields')
} else {
$('#form').submit();
}
});

关于javascript - 如何在 JavaScript 中最少输入两个表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35341662/

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