Li3ro
Li3ro

Reputation: 1877

Toggling color of Text Input with Button click - jQuery

$("#btn").button().click(function() {
    $("#textinput").css('color',function(clr) {
        if ($("#textinput").css('color') == '#000000')
            return '#ff0000';
        else
            return '#000000';
    });
});

for some reason I cant toggle between the colors in input text. the .css docs of jQuery states the following:

Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

in general, how can i get the property value of UI object (css values are constant?) ?

thnx!

Upvotes: 0

Views: 696

Answers (1)

Rumplin
Rumplin

Reputation: 2768

I would create a class .white and a class .black and use .addClass() and .removeClass(). A html element can have multiple classes set

$("#btn").button().click(function() { 
    if ($("#textinput").hasClass("white"))
    {
        $("#textinput").removeClass("white").addClass("black");
    }
    else {
        $("#textinput").removeClass("black").addClass("white");
    }
}); 

I think someone will post a more elegant solution to this, because I think this is too much code for a simple task like this.

update: Use toggleClass instead: http://api.jquery.com/toggleClass/

Upvotes: 1

Related Questions