简体   繁体   中英

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. I'm very new to JavaScript so I don't really know what I did wrong. 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 :)

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

Since you are already using jQuery, you can simplify that code to a great extent. 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. Add a class to all input fields , eg class="required" and add attribute fieldname with respective value for each input field.

     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

$("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;}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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