1

I've a input a button which have a initial background image. I tried to change its image when some condition changed with jquery .css(). It seems that it will override the button's global css in css file. How can I only change background attribute with jquery or anything else? Thanks.

JS:

if(sum>=window.start_fee){
    $(".shopcart").removeAttr("disabled")
    $(".shopcart").css("background", 'url(/static/images/cart2.png)')
}else{
    $(".shopcart").attr("disabled","disabled")
    $(".shopcart").css("background", 'url(/static/images/cart.png)')
}

css:

.shopcart{
     background:url(/static/images/cart.png) no-repeat; 
     border:none; 
     background-size:100% 100%; 
     width:57px; height:50px; 
     float:right;
}
user1179442
  • 473
  • 5
  • 16
  • 2
    The code you have is correct. It's not going to alter any global CSS, just change the specific class you targeted. If you reload the page it will revert to what's in your CSS file. – Dave Nov 21 '14 at 06:53
  • Hope this would be useful [click here](http://stackoverflow.com/questions/512054/setting-background-image-using-jquery-css-property) – Nayana_Das Nov 21 '14 at 06:58

2 Answers2

3

The best thing to do is create a class disabled in css, in this way you separate the presentation of logic. Sample

CSS

.shopcart{
     background:url(/static/images/cart2.png) no-repeat; 
     border:none; 
     background-size:100% 100%; 
     width:57px; height:50px; 
     float:right;
}

.shopcart.disabled{
     background:url(/static/images/cart.png) no-repeat; 
}

In JS you just add or remove the disabled class, sample:

JS

if(sum>=window.start_fee){
    $(".shopcart").removeClass("disabled");
}else{
    $(".shopcart").addClass("disabled");
}
Queli Coto
  • 686
  • 7
  • 9
1

Instead of Remove attr you can use addClass and removeClass property

$(document).ready(function(){
if(sum>=window.start_fee){
    $("input[type=submit]").removeClass("submitbtn");
    $("input[type=submit]").addClass("submitbtnnew");   
}
else{
    $("input[type=submit]").addClass("submitbtn");
    $("input[type=submit]").removeClass("submitbtnnew");

}

});
</script>

Apply your background image for that class

<style>
.submitbtn{
    background:#000;
}
.submitbtnnew{
    background:#03C;
}
</style>
nikita
  • 273
  • 3
  • 15