Michael Casunuran Michael Casunuran - 1 month ago 9
CSS Question

I have some issue with jquery css method

I want to change the color of the button when it is clicked using this code

$('.vote').click(function(){
var self = $(this);
var type = $(this).data("type");
var action = $(this).data("action");
var parent = self.parent();
if(!(status == '1')){
if(type == '1'){
self.css("color","orange");
}
else if(type == '2'){
self.css("color":"red"});
}
}
});


And it is not working. But when I try to put this line
self.css("color","orange");
outside the IF statement it is working :

$('.vote').click(function(){
var self = $(this);
var type = $(this).data("type");
var action = $(this).data("action");
var parent = self.parent();
self.css("color","orange");
if(!(status == '1')){
if(type == '1'){
//if statement here
}
else if(type == '2'){
//if statement here
}
}
});


The problem is that it is not what I want to happen. How can I make it happen using the first code above.

Answer

The problem appear to be in the following line :

self.css("color":"red"});

You've missed to open bracket { here :

self.css({"color":"red"});
_________^

Or just use comma , as you do in first example :

self.css("color","red");

Hope this helps.

 var status = '2';

$('.vote').click(function(){
  var self = $(this);
  var type = $(this).data("type");
  var action = $(this).data("action");
  var parent = self.parent();

  if(!(status == '1')){
    if(type == '1'){
      self.css("color","orange");
    }
    else if(type == '2'){
      self.css({"color":"red"});
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class='vote' data-type='1'>Vote type 1</button>
<button class='vote' data-type='2'>Vote type 2</button>

Comments