Reputation: 4597
I have an html special character I want to toggle off and on like a check box. In this instance, it's a star: ☆ that can become filled in: ★.
I want to check the state of the star when it is clicked.
$(".action_table_star").click(function() {
if ($(this).html() == "★") {
$(this).html("☆");
$(this).css('color', 'white');
} else {
$(this).html("★");
$(this).css('color', 'rgb(255,165,0)');
}
});
This doesn't work though because $(this).html() is never equal to "★". How can I rewrite this if statement to I guess decode the html special character and check it's "state"?
Upvotes: 1
Views: 3426
Reputation: 92973
Improving on SpYk3HH's suggestion, I would approach this by adding both stars to the document, one with display:none
, and use jQuery to toggle them both on click.
An additional benefit is that you can now style each star individually with CSS instead of jQuery, which is as it should be.
HTML:
<div class="action_star">
<span class="star1">★</span>
<span style="display:none" class="star2">☆</span>
</div>
JS:
$('.action_star').click(function() {
$(this).find('.star1,.star2').toggle();
});
Less code, more clear, more readable, much better.
Upvotes: 0
Reputation: 22580
My suggestion would be not to depend on a character but a class added and removed instead, like so:
$(".action_table_star").click(function(e) {
if ($(this).hasClass("star-checked")) {
$(this).css('color', 'rgb(255,165,0)').text("☆");
}
else {
$(this).css('color', '#fff').text("★");
};
$(this).toggleClass("star-checked");
})
Upvotes: 1
Reputation: 349142
Instead of using .html()
, use .text()
in conjunction with a \uxxxx
sequence, or String.fromCharCode()
.
$(".action_table_star").click(function() {
if ($(this).text() == String.fromCharCode(9733)) {
$(this).html("☆");
$(this).css('color', 'white');
} else {
$(this).html("★");
$(this).css('color', 'rgb(255,165,0)');
}
});
When the \uxxxx
method is used, you have to convert the base-10 numeric charcode to a base-16 one. Example (in console):
(9734).toString(16);
// Returns 2606. Now, paste `"\u2606"` in your code
Don't forget to padd sufficient zeros to get 4 digits.
Upvotes: 2
Reputation: 7895
No, $(this).html()
will never equal ★
, but it will equal ★
$(".action_table_star").click(function() {
if ($(this).html() == "★") {
$(this).html("☆");
$(this).css('color', 'green');
} else {
$(this).html("★");
$(this).css('color', 'rgb(255,165,0)');
}
});
Upvotes: 0
Reputation: 14654
This seems to work
escape($(this).html()) == "%u2605"
where %u2605
is the the filled star symbol escaped.
Upvotes: 1