Manoj Shrestha
Manoj Shrestha

Reputation: 4684

JQuery Form Validation

I need to do a form validation with jQuery. But I'm having a problem in this.

I have a HTML form as below:

<FORM id="formID" method="POST" onsubmit="return checkRequiredFields(this)" action="">
   <td><input class="required" type="text" id="input1" value="" /></td>
   <td><input class="required" type="text" id="input2" value=""/> </td>
   <td><input class="required" type="text" id="input3" value=""/> </td>
   <td><input type="text" id="input4" value=""/> </td>
   <td><input type="submit" id="save" value="Save" /></td>
</FORM>

The first three input text fields are required fields. I tried writing the script like below:

<script type="text/javascript">
function checkRequiredFields(form){
    var no_errors = true;
    $(form).find(".required").each(function(){
        alert("Inside Loop");
           var field = $(this);
        if (field.val() == ""){
            $("#"+field ).css("color","red");
            no_errors = false;
        } else {    
            $("#"+field ).css("color","white");
        }
    });
    return no_errors;
}

</script>

But, the above code is not working as I expected. The alert() is never executed, meaning that the control does not find any element with class "required". So, what is the problem in my code?

Upvotes: 0

Views: 184

Answers (1)

Jasper
Jasper

Reputation: 75993

$("#"+field ).css("color","red"); is not right. field is an object not a string, but since it's already a jQuery object you can just do this: field.css("color","red");. You'll have to do that for the other .css() call too: $("#"+field ).css("color","white"); => field.css("color","white");

Here is a demo: http://jsfiddle.net/eehV6/

Upvotes: 3

Related Questions