1

我想检查输入字段是否具有所需的属性。如果这些字段具有空值,并且还具有必需的属性,则在每个字段后附加一个错误 div。在使用选择器时我有点难过

 // initialize validator for a bunch of input fields
 var inputs = $("#Contact :input")

 // Check all required fields
 if (inputs.attr("required") && inputs.val() === "") {
    var invalidFields = Select all fields that have the attribute required and an empty value, and assign them a class
     alert("Required Fields not completed"); 
 }
4

4 回答 4

2

循环遍历每个元素应该做到这一点

$("#Contact :input [required]").each(function(){
if($(this).val()===""){
//the input doesn't have a value, but is required
//code here
}
});
于 2012-04-06T01:38:16.533 回答
0

您可以将该filter函数与回调一起使用,以将所选元素缩小到缺少所需的元素:

var inputs = $("#Contact :input");

var missing = inputs.filter(function() {
   return this.getAttribute("required") && this.value === "";
});
于 2012-04-06T01:29:28.140 回答
0

尝试这样的事情,它应该为所有符合条件的输入添加类

  $("#Contact :input").each(function(){
         if ($(this).attr("required") && $(this).val() === "") 
         {
        $(this).addClass("req");

         }
      });
于 2012-04-06T01:31:46.427 回答
0

试试这个:http: //jsfiddle.net/aramk/mK8YL/

HTML:

<input id="some" class="required" name="some" type="text" value="" />
<input id="submit_btn" type="submit" value="Go!" />

JS:

$(document).ready(function() {

    $('#submit_btn').click(function() {
        // initialize validator for a bunch of input fields
        var valid = true;
        var inputs = $("input.required").each(function() {
            var input = $(this);
            // Check all required fields
             if (input.val() === '') {
                input.addClass('invalid');
                valid = false; // Avoid a submit
                alert("Required Fields not completed"); 
             } else if (input.hasClass('invalid')) {
                 input.removeClass('invalid');
             }
        });
        if (valid) {
            // This will submit
            alert('submit successful');
        } else {
            return false;
        }
    });

}
);
​

CSS:

.required {
    background: yellow;
    color: black;
}

.invalid {
    background: red;
    color: white;
}​

确保将这些输入添加到表单中以供提交。

于 2012-04-06T01:36:00.573 回答