stack stack - 4 months ago 7
Javascript Question

How can I create a marking an answer as accepted one system?

Explanation: I'm trying to make an accepted-answer system and there are three cases:


  • marking a new answer as accepted one (there is no accepted answer already)

  • undo a accepted answer

  • switching from one answer to another one



Here is my code:



$("body").on('click', '.fa-check', function(e) {

// send a request by ajax and if it is successful then

if( this.attr('color') == '#44b449' ){ // undo
this.css({"color":"#aaa"}); // set gry color to marked icon
} else { // switchin or marking a new one
$('.fa-check').css({"color":"#aaa"}); // set gray color to all icons
this.css({"color":"#44b449"}); // set green color to marked icon
}

});

.fa-check{
color:#aaa;
cursor: pointer;
}

.fa-check:hover{
color: #999;
}

<script src="https://use.fontawesome.com/9e9ad91d21.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>answer1</p>
<i class="fa fa-check" aria-hidden="true"></i>
<hr>
<p>answer2</p>
<i class="fa fa-check" aria-hidden="true" style="color: #44b449;"></i>
<hr>
<p>answer3</p>
<i class="fa fa-check" aria-hidden="true"></i>





But as you see my code doesn't work. How can I fix it?

Note: The whole of my question is about coloring.

Answer

Firstly your code is throwing errors as you're calling jQuery methods on this when it refers to a DOMElement, not a jQuery object.

To fix your issues you can simplify your logic by using classes instead of applying inline CSS styling. This allows you to simply toggle the class on click of the .fa-check element. Try this:

$("body").on('click', '.fa-check', function(e) {
  // send a request by ajax and if it is successful then
  
  $('.fa-check').not(this).removeClass('checked');
  $(this).toggleClass('checked');
});
.fa-check {
  color: #aaa;
  cursor: pointer;
}

.fa-check.checked {
  color: #44b449;
}
<script src="https://use.fontawesome.com/9e9ad91d21.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>answer1</p>
<i class="fa fa-check" aria-hidden="true"></i>
<hr>
<p>answer2</p>
<i class="fa fa-check checked" aria-hidden="true"></i>
<hr>
<p>answer3</p>
<i class="fa fa-check" aria-hidden="true"></i>

Comments