met.lord
met.lord

Reputation: 618

CoffeeScript: Line-Through on LI after Checkbox is checked

I'm using CoffeeScript for an app on Rails and right now after a checkbox is changed I call a jquery function to update its value on the database using ajax, but I'd also like to put a line through if the checkbox is selected.

HTML:

    <ul>
       <li class="side-bar-element">
           <input class="task" id="1" name="1" type="checkbox" value="Element 1"/>
           Element 1
       </li>
       <li class="side-bar-element">
           <input class="task" id="2" name="2" type="checkbox" value="Element 2"/>
           Element 2
       </li> 
       <li class="side-bar-element">
           <input class="task" id="3" name="3" type="checkbox" value="Element 3"/>
           Element 3
       </li> 
       <li class="side-bar-element">
           <input class="task" id="4" name="4" type="checkbox" value="Element 4"/>
           Element 4
       </li>  
    </ul>

CoffeeScript:

$(".task").live "change", ->
  id = $(this).attr("id")
  isChecked = $(this).attr("checked")
  $.ajax
    url: "/update"
    type: "post"
    data: { id }

    success: ->
      alert "Updated Succesfully."
      if(isChecked)
        alert "For Testing: Is Checked."
        $(this).closest('li').css "text-decoration", "line-through"

    error: ->
      alert "Changes were not saved."

What I don't understand is why the alert "Is Checked" works fine but it never updates the CSS. I also tried using parent(), prev() but no luck. Any help would be really appreciated. Thanks.

Upvotes: 1

Views: 1079

Answers (1)

Prinzhorn
Prinzhorn

Reputation: 22518

this inside the success callback is not what you think it is.

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

Use

$.ajax
    context: this,
    url: "/update"
    type: "post"
    data: { id }
    //.....

$.ajax has a ton of other options as well http://api.jquery.com/jQuery.ajax/

Upvotes: 3

Related Questions