javascript jQuery 检查表单中所有必需的输入是否不为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47532202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:26:37  来源:igfitidea点击:

jQuery check if all required inputs from a form are not empty

javascriptjqueryattributesrequired

提问by Bogdan C

Imagine a simple form with method POSTand 30 inputs.

想象一个带有方法POST和 30 个输入的简单表单。

I would like to create a jQuery function that will be called from submit button. I searched about how to check all inputs that are required, but didn't find anything to help.

我想创建一个将从提交按钮调用的 jQuery 函数。我搜索了如何检查所有必需的输入,但没有找到任何帮助。

I would like something like this:

我想要这样的东西:

var inputs_required = all inputs from my form which have attribute required;
function check_required_inputs() {
   if(inputs_required != "") {
     //create ajax with serialize() and submit form;
   }
} else {
   //highlight inputs that are empty and show a message;
}

Can this be achieved in jQuery?

这可以在jQuery中实现吗?

回答by SuperMrBlob

Zakaria already posted an answer, which should work great. Alternatively, instead of having a custom class, you could instead find all input, textareaand selectelements that have the attribute requiredand are visibleusing

Zakaria 已经发布了一个答案,应该很好用。或者,而不是有一个自定义类,可以转而找到所有inputtextareaselect元素有属性required,并visible使用

var required = $('input,textarea,select').filter('[required]:visible');

And then iterate through them using each()etc.

然后使用each()等迭代它们。

Example:

例子:

var allRequired = true;
required.each(function(){
    if($(this).val() == ''){
        allRequired = false;
    }
});

if(!allRequired){
    //DO SOMETHING HERE... POPUP AN ERROR MESSAGE, ALERT , ETC.
}

回答by Zakaria Acharki

You could give all your required inputs a common class (requiredfor example) then use each()to loop through them like :

您可以为所有需要的输入提供一个通用类(required例如),然后使用each()它们来循环,例如:

function check_required_inputs() {
    $('.required').each(function(){
        if( $(this).val() == "" ){
          alert('Please fill all the fields');

          return false;
        }
    });
    return true;
}

回答by user3154108

jQuery('button').on('click', function() {
  jQuery('input:invalid').css('background-color','red');
  jQuery('input:valid').css('background-color','green');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" required="true" />
</form>
<button>click</button>

You simply give the inputs the required="true"attribute, then all empty required inputs will have the pseudo class :invalid.

您只需为输入提供required="true"属性,然后所有空的必需输入都将具有伪类:invalid

jQuery('input:invalid')gives you a list of all invalid inputs. .lengthwill give you the length of said list, if the length is > 0, your form is invalid.

jQuery('input:invalid')为您提供所有无效输入的列表。.length将为您提供所述列表的长度,如果长度 > 0,则您的表单无效。

回答by samehanwar

you can try this assume that the form has an IDof form-action and submit button of IDform- submit.

你可以尝试这个假设表单有一个ID表单操作和表单提交按钮ID

var submitButton = $('#form-submit'),
    formContainer  = $('#form-action');

    submitButton.on('click',function(e){
      e.preventDefault();
      formContainer.find('input').each(function(index,ele){
        if(ele.value === null || ele.value === ''){
            var error  = " the " + ele.name + " field  is requird ";
                ele.after(error);
           }
     });
});   

回答by Carl Edwards

You could also leverage the iterable function, every(), which will either return trueonly if everyinput validation is satisfied or falseif otherwise:

您还可以利用可迭代函数every(),它要么true仅在满足每个输入验证时返回,要么false在其他情况下返回:

function check_required_inputs() {
   var valid =  Array.prototype.every.call($('.required'), function(input) {
     return input.value;
   });

   if (valid) {
     return true;
   } else {
     alert('Please fill all the fields');

     return false;
   }
}

回答by Balthazar DOSSOU

I created this function which checks if the field is empty not only but if the user has inserted one or spaces without putting a character from a to b or other

我创建了这个函数,它不仅检查该字段是否为空,而且还检查用户是否插入了一个或多个空格而没有将字符从 a 放入 b 或其他

function checkfield (champ)
{
var off='', isit=false;
for (var j=0; j <champ.val ().trim ().split (' ').length;j++)
{
off+=champ.val ().split (' ')[j];
}
off.replace (' ', '');
if (off.length==0) isit=true;
return isit;
}

to use :

使用:

example

例子

if (checkfield ($('.class_of_field'))==true) return;