Maximus Decimus
Maximus Decimus

Reputation: 5291

Assign a background image with jquery

I'm trying to assign an image to a label depending on the status of a checkbox, but it's not working

Javascript

        var myLabel = $('[id$=lbl]');
        var myCheckBox = $('[id$=chk]');
        if (myCheckBox.prop('checked'))
        {
            //myLabel.css('background-image', myLabel.data("image1"));
            myLabel.css({backgroundImage : myLabel.data("image1")});
            alert(myLabel.data("image1"));
        }
        else
        {
            myLabel.css({backgroundImage : myLabel.data("image2")});
            alert(myLabel.data("image2"))
        }
        alert(myLabel.css('background-image'));

The state of the checkbox is working well (true or false) The alerts with myLabel.data("image1") and myLabel.data("image2") returns the url of the images [url(../images/active.png) no-repeat; and url(../images/inactive.png) no-repeat;]

no matter how you assign the value

            myLabel.css('background-image', myLabel.data("image1"));

or

            myLabel.css({backgroundImage : myLabel.data("image1")});

the label it is still retaining the first assigned image at the moment of the load page. So the label is always with active image. What am i doing wrong?

Upvotes: 0

Views: 283

Answers (2)

Maximus Decimus
Maximus Decimus

Reputation: 5291

I found the problem

As I said in my question I was assigning the image like this url(../images/active.png) no-repeat but the css property was wrong. Instead of using the backgroundImage or background-image, finally I used the "background" and period. the "no-repeat" part was causing a problem.

myLabel.data("image1") = "url('../images/active.png') no repeat;";
myLabel.css("background" : myLabel.data("image1"));

Or you can do this also if you want to use the background-image property.

myLabel.data("image1") = "url('../images/active.png')";
myLabel.css("background-image" : myLabel.data("image1"));
myLabel.css("background-repeat" : "no-repeat");

Upvotes: 0

Anand Jha
Anand Jha

Reputation: 10724

try this,

   var myLabel = $('[id$=lbl]');
    var myCheckBox = $('[id$=chk]');
    if (myCheckBox.prop('checked'))
    {


        myLabel.removeClass('active')
        myLabel.addClass('inactive');

    }
    else
    {
        myLabel.removeClass('inactive')
        myLabel.addClass('active');
    }

and define the css like

.active{background-image:url(../images/active.png) no-repeat; }
.inactive{background-image:url(../images/inactive.png) no-repeat;}

Upvotes: 1

Related Questions