Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Why isn't the jQuery addClass method working here?

Environment

I have a set of validation functions:

var firstName = $('#FirstName'),
    lastName = $('#LastName'),
    dateOfBirth = $('#DateOfBirth'),
    city = $('#City'),
    phone = $('#Phone'),
    email = $('#Email'),
    insType = $('#InsType'),
    otherInsType = $('#OtherInsType'),
    insID = $('#InsID'),
    service = $('#Service'),
    otherService = $('#OtherService'),
    comments = $('#Comments'),
    outOfPocket = $('#OutOfPocket'),
    permission = $('#Permission'),
    signature = $('#Signature');

function formIsValid() {
    if (missingRequiredField([
        firstName, lastName, dateOfBirth, city, phone, email,
        insType, insID, service, comments, outOfPocket, permission,
        signature
    ])) {
        alert('There is a missing required field.');
        return false;
    }

    alert('The form was valid.');

    return false;
}

function missingRequiredField(objs) {
    var hasError = false;
    objs.forEach(function(o) {
        if (!$(o).val()) {
            $(o).addClass('error');
            hasError = true;
        }
    });

    return hasError;
}

and I know they work because when I leave the fields blank I get the alert('There is a missing required field.');. But for some reason the $(o).addClass('error'); isn't actually adding the class. I know the class works because if I add it by hand the visual style looks like I want. Further, I know it's not adding the class because I check out the element in Firebug after getting the alert.

Am I missing something here? I thought it was this straight forward -even checked with the jQuery documentation and it looks right to me.

Here is an example of one of the fields in markup as well:

<div>
    <label for="FirstName">First Name</label>
    <input type="text" id="FirstName" name="FirstName" />
</div>

EDIT

I even pulled the forEach out into a basic for loop and the addClass still isn't take. The function is working because hasError returns true when a field doesn't have a value -just that stubborn addClass. NOTE: I did pull off the unnecessary $ surrounding the o in this version.

function missingRequiredField(objs) {
    var hasError = false;
    for (var i = 0; i < objs.length; i++) {
        var o = objs[i];
        if (!o.val()) {
            o.addClass('error');
            hasError = true;
        }
    }

    return hasError;
}

Upvotes: 2

Views: 1038

Answers (3)

bibu mathew
bibu mathew

Reputation: 1

//this code should fix the problem

$(function(){
var firstName = $('#FirstName'),
    lastName = $('#LastName'),
    dateOfBirth = $('#DateOfBirth'),
    city = $('#City'),
    phone = $('#Phone'),
    email = $('#Email'),
    insType = $('#InsType'),
    otherInsType = $('#OtherInsType'),
    insID = $('#InsID'),
    service = $('#Service'),
    otherService = $('#OtherService'),
    comments = $('#Comments'),
    outOfPocket = $('#OutOfPocket'),
    permission = $('#Permission'),
    signature = $('#Signature');

function formIsValid() {
    if (missingRequiredField([
        firstName, lastName, dateOfBirth, city, phone, email,
        insType, insID, service, comments, outOfPocket, permission,
        signature
    ])) {
        alert('There is a missing required field.');
        return false;
    }

    alert('The form was valid.');

    return false;
}

function missingRequiredField(objs) {
    var hasError = false;
    objs.forEach(function(o) {
        if (!$(o).val()) {
            $(o).addClass('error');
            hasError = true;
        }
    });

    return hasError;
}

});

Upvotes: 0

Maloric
Maloric

Reputation: 5605

It works in the following jsFiddle example: http://jsfiddle.net/nHHyQ/

Admittedly I am only using one field to test. I know it sounds obvious, but have you styled up the error class? Double check the spelling and the selector in your css.

Javascript: var firstName = $('#FirstName'); $(document).ready(function () { $('#test').click(function (e) { formIsValid(); }); });

function formIsValid() {
    if (missingRequiredField([
    firstName])) {
        alert('There is a missing required field.');
        return false;
    }

    alert('The form was valid.');

    return false;
}

function missingRequiredField(objs) {
    var hasError = false;
    objs.forEach(function (o) {
        if (!$(o).val()) {
            $(o).addClass('error');
            hasError = true;
        }
    });

    return hasError;
}

Upvotes: 0

Corion
Corion

Reputation: 663

The jQuery selectors are running before the DOM is ready, which means no elements are being selected (since they haven't been build yet).

If you select the elements after the DOM is ready, it works.

$(document).ready(function() { 
    firstName = $('#FirstName');
    lastName = $('#LastName');
});

Additionally, as other people have stated, you should convert the .foreach() loop into a regular for loop.

See the following jsbin for the example:

http://jsbin.com/uzefeg/3/edit

Upvotes: 2

Related Questions