Guilherme Henrique Guilherme Henrique - 1 month ago 8
Javascript Question

ternary operator does not change backgroundColor

i'm trying to set background when input is null and keep this value when have some

function emptyto(element){
return element.value == '' ? element.style.backgroundColor = "#ccc" : element.val()
}

Answer

You just have your assignment in the wrong place:

function emptyto(element){
    return element.style.backgroundColor = element.value == '' ? "#ccc" : element.val();
    // ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

Separately: DOM elements don't have a val method. You either wanted to use value in both places:

function emptyto(element){
    return element.style.backgroundColor = element.value == '' ? "#ccc" : element.value;
    // ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

Or if you're using jQuery, to wrap the element and use val in both places (along with css):

function emptyto(element){
    var $el = $(element);
    return $el.css("backgroundColor", $el.val() == '' ? "#ccc" : $el.val());
}

Actually, since '' is a falsy value, we can use the curiously-powerful || operator1 to simplify that:

function emptyto(element){
    return element.style.backgroundColor = element.value || "#ccc";
}

1 (That's a post on my anemic little blog.)

Comments