Ryan
Ryan

Reputation: 787

only one of two variables is being actioned in jquery if statement

When the user clicks on the 'Review' button, an overlay appears, showing them which form fields are yet to be satisfactorily completed. I have an object array which keeps track of each form field, and assigns either 'verified' or 'unverified' to that form element.

Within the overlay, those fields that are unverified should appear with a red background colour and those verified, in green. As well as this, either 'Complete' or 'Not complete' appears as appropriate next to each form field reference.

When I run the following code, the correct 'Complete'/'Not complete' label appears, however the colour remains red. I don't understand how one variable within the if statement can be updated (status) and yet the other is not (color).

My code is as follows:

$("#review").click(function() {
    var status = "";
    var color = "";

    //Show the modal dialog
    showModal(dialog);

    //Determine the content of the modal dialog
    $("#cl").empty();
    $.each(object, function(key, element) {
        if (element.status == "unverified") {
            status = "Not complete";
            color = "#ef8f8b";
        } else {
            status = "Complete";
            color = "#bfef8b";
        }

        $("#cl").append("<tr><td class='td-left'>"+element.review+"</td><td class='td-right'>"+status+"</td></tr>");
        $("#cl .td-left").css("background-color", color);
    });
});

Upvotes: 0

Views: 79

Answers (1)

Kevin B
Kevin B

Reputation: 95027

$("#cl .td-left").css("background-color", color); updates all elements that match, not just the one you most recently added. Try targeting only the new one.

$("#cl .td-left:last").css("background-color", color);

or better yet, edit it before you append it.

$("<tr><td class='td-left'>"+element.review+"</td><td class='td-right'>"+status+"</td></tr>")
    .css("background-color", color)
    .appendTo("#cl");

Upvotes: 3

Related Questions