简体   繁体   English

验证输入和复选框

[英]Validate inputs & checkboxes

I have a form where I need to validate only the checked checkboxes, their file and text input are filled. 我有一个表单,我只需要验证选中的复选框,即会填充其文件和文本输入。 My issue is when two or more checkboxes are checked and one row is filled correctly, but the other or others aren't filled correctly, it submits with some errors. 我的问题是,选中两个或多个复选框并且正确填充了一行,但另一行或其他未正确填充时,它提交了一些错误。

I have been searching for a solution with no luck, here is my code: 我一直在寻找一个没有运气的解决方案,这是我的代码:

function send()
{
$('input[type=checkbox]:checked').each(function () {
 var vals = $(this).val();
 var arch = document.getElementById(vals);
 var rcant = document.getElementById("ke"+vals); 

 if(arch.value==""){
    arch.required = true;
    alert("Please select the file to send");
    arch.focus();
 }else    
 if(rcant.value==""){
    rcant.required = true;
    alert("Please write the quantity to send");
    rcant.focus();
 }

 if(arch.value != "" && rcant.value != "")
 {
    formula.submit();
 }

});
}  

EDIT: 编辑:

错误

if two checkboxes are checked, one is filled but the other is blank, it trows me the error & focuses but it submits and the form do the work and the result I get sql warning and the email is filled with blank spaces that the inputs should be filled 如果选中了两个复选框,则一个被填充,但另一个为空,它向我抛出错误和焦点,但是它提交并且表单完成了工作,结果我得到sql警告,电子邮件中填充了空格,输入应变得充实

The problem is that you submit the form inside the .each() loop, so it submits as soon as it finds one checkbox whose inputs are filled in correctly. 问题是您在.each()循环中提交了表单,因此一旦找到一个复选框,其输入正确填写,它便立即提交。

Instead, use a variable to keep track of whether you found any validation errors during the loop. 而是使用变量来跟踪在循环过程中是否发现任何验证错误。 Then check the variable at the end of the loop. 然后在循环结束时检查变量。

 function send() { var form_ok = true; $('input[type=checkbox]:checked').each(function() { var vals = $(this).val(); var arch = document.getElementById(vals); var rcant = document.getElementById("ke" + vals); if (arch.value == "") { arch.required = true; alert("Please select the file to send"); arch.focus(); form_ok = false; return false; // stop looping once we find an error } else if (rcant.value == "") { rcant.required = true; alert("Please write the quantity to send"); rcant.focus(); form_ok = false; return false; // stop looping once we find an error } }); if (form_ok) { formula.submit(); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM