1

I am wanting to check if input fields have the attribute required. If these fields have an empty value, and also have the attribute required, append an error div after each field. I got a little stumped when it comes to using the selector

 // 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 Answers 4

2

Looping through each element should do it

$("#Contact :input [required]").each(function(){
if($(this).val()===""){
//the input doesn't have a value, but is required
//code here
}
});
Sign up to request clarification or add additional context in comments.

Comments

0

try something like this it should add class to all inputs that meet the criteria

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

         }
      });

Comments

0

You can use the filter function with a callback to narrow down the selected elements to missing required ones:

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

var missing = inputs.filter(function() {
   return this.getAttribute("required") && this.value === "";
});

Comments

0

Try this: 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;
}​

Make sure to add those inputs into a form for submission.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.