0

I have a code where when a checkbox is checked, the list item that the checkbox is contained in is supposed to fade out from view. Here is my current code:

 $(document).on('change', '.task', function(){
var id = $(this).attr('id');
          $.ajax({
            url: '/task/'+id,
            method: 'POST',
            data: {'_method' : 'PUT'},
            dataType: 'json',
            success:function(json){

              if(json.isSent){
                alert('Task Updated Successfully!');
                $(this).closest('li').fadeOut(500);
              }

            }
          });
}

And here is my html (Note: I am using Laravel, so some of the html contains Blade code, but it does work properly)'

 @foreach ($return['Tasks'] as $task)
        <li class="list-group-item">
            <div class="form-group">
                <label class="control-label">{{ $task->name }} (Due on {{ $task->timeDue->format('l\\, F jS \\a\\t h:i:s A') }})</label>
                <div class="float-left">
                    <input type="checkbox" id="{{ $task->id }}" class="big-checkbox task" />
                </div>
            </div>
        </li>
      @endforeach

When I check the checkbox, the "Task Updated Successfully" alert shows up, so I know that the code is running, but the fadeOut won't do anything. There are no errors in the console either to tell me what went wrong, it just won't fade out.

Eric Brown
  • 1,312
  • 3
  • 15
  • 30
  • 2
    Possible duplicate of [$(this) inside of AJAX success not working](https://stackoverflow.com/questions/6394812/this-inside-of-ajax-success-not-working) - *"Inside the callback, `this` refers to the jqXHR object of the Ajax call, not the element the event handler was bound to."* – Tyler Roper Jun 06 '17 at 17:22

1 Answers1

2

I believe your scope is lost (this). Try that instead

$(document).on('change', '.task', function(){
      var o = $(this);    
      var id = $(this).attr('id');
          $.ajax({
            url: '/task/'+id,
            method: 'POST',
            data: {'_method' : 'PUT'},
            dataType: 'json',
            success:function(json){

              if(json.isSent){
                alert('Task Updated Successfully!');
                o.closest('li').fadeOut(500);
              }

            }
          });
}
Eric
  • 9,870
  • 14
  • 66
  • 102