简体   繁体   English

检查输入字段是否填写在表单中

[英]Check if input fields are filled out in a form

I have a form myForm and I want to check if specific input field are filled out before sending the form. 我有一个表单myForm ,我想检查在发送表单之前是否填写了特定的输入字段。 I'm very new to JavaScript so I don't really know what I did wrong. 我是JavaScript的新手,所以我真的不知道我做错了什么。 Any help is welcomed. 欢迎任何帮助。

function validateForm() {
    var validate = true;
    var alert_string = "";
    var children = $("#myForm").children("input");
    console.log(children.size());
    for(var i = 0; i < children.length ; i++){
        if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
            if(children[i].attr(id) == null || children[i].attr(id) == ""){
                validate = false;
                alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
            }
        }
    }
    alert_string = alert_string.concat("must be filled out !");
    if(validate == false){
        alert(alert_string);
        return false;
    }
    return true;
}
children[i].attr(id) == ""   // wrong

You don't have to check whether their id s are null, you have to check whether their value s are empty :) 你不必检查他们的id是否为null,你必须检查他们的是否为空:)

if(children[i].value == "")

Since you are already using jQuery, you can simplify that code to a great extent. 由于您已经在使用jQuery,因此可以在很大程度上简化该代码。 For example a simple "all fields filled" check can be 例如,可以使用简单的“所有字段填充”检查

var flag=0;
$('#myForm').each(function() {
    if ( $(this).val() === '' )
         flag=1;
});

if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. 如果您将使用jQuery,您可以检查输入字段是否为空并且还会捕获空格/秒。 Add a class to all input fields , eg class="required" and add attribute fieldname with respective value for each input field. 向所有输入字段添加一个类,例如class =“required”,并为每个输入字段添加具有相应值的属性fieldname。

     var requiredFields = "";
        $("#myForm").find('.required').each(function () {
            if ($(this).val().trim().length == 0) {
                requiredFields += " - " + $(this).attr("fieldname") + "\n";
            }
        });

        if (requiredFields != "") {
            alert("Please enter the following required field(s): \n" + requiredFields);
        } else {
            //save here
        } 

You can use required like <input required type="text" name="email" id="log" /> or use jQuery like 您可以使用required <input required type="text" name="email" id="log" />或使用jQuery之类的

$("form").submit(function() { 
    var has_empty = false;
    $(this).find('input').each(function() {
        if(! $(this).val()) {
            has_empty = true; 
            return false;
        }
    });
    if(has_empty){return false;}
});

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

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