简体   繁体   English

仅在所有必填字段均已填写时才提交表单吗?

[英]Submit form only if all required fields are full?

I want to do form.submit() but only if all form items with the required attribute are full. 我想做form.submit(),但前提是所有具有required属性的表单项都已满。

I was thinking on simpy iterating through the form children in search for the attribute, but I'm not sure how to do it since there might be nested elements and such. 我正在考虑通过子级表单进行simpy迭代以搜索属性,但是由于可能存在嵌套元素等,因此我不确定该怎么做。 And probably there is an easier way to do it. 也许有一种更简单的方法可以做到这一点。

this.form_is_full = function(form){
    for (var i = 0; i < form.elements.length; i++){
        if(form.elements[i].getAttribute("required") && form.elements[i].value=="")
        {
        // If has attribute required and is blank return false
        }
    }
    return true;
}

How can I do this? 我怎样才能做到这一点?

Try this: 尝试这个:

$('#YourFormId').submit(function(e) {
    if ($.trim($("#YourFormId input").val()) === "") {
        e.preventDefault();
        alert('you did not fill out one of the fields');
    }
});
function Validate()
        {


        // create array containing textbox elements
        //for example:
        var inputs = [document.getElementById('fname'), 
        document.getElementById('lname'), document.getElementById('email'), 
        document.getElementById('messagetxt')];

        var error;

        for(var i = 0; i<inputs.length; i++)
        // loop through each element to see if value is empty
        {
            if(inputs[i].value == '')
            {
                error = 'Please complete all fields.';
                alert(error);
                return false;
                }
        }
     }

This is what I did: 这是我所做的:

this.validate_form = function(form){
    for (var i = 0; i < form.elements.length; i++){
        if(form.elements[i].value == "" && form.elements[i].getAttribute("name") && form.elements[i].hasAttribute("required"))
        {
            return false;
        }
    }
    return true;
}

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

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