Search code examples
jqueryjquery-selectors

jQuery .next() not working, element stays empty


I am trying to add html to a div using jQuery .next() but I get no results.

This is the html part :

<div class="widget widget_border">

  <h3 class="widget_border" id="widget_lot">Last opened tasks 
      <div class="dashboard_dd_arrow"></div>
  </h3>
  <div class="widget_content"></div>
</div>

and JavaScript:

(document).ready(function () {
  $('.widget h3').on('click', function () {
    if (!$.trim($(this).next('.widget_content').html())) {
      // if this widget don't have any data send ajax and load it

      var widget_id = $(this).attr('id');
      switch (widget_id) {
      case 'widget_lot':
        $.ajax({
          type: 'POST',
          url: '/dashboard/ajax_last_opened_tickets',
          data: {},
          success: function (data) {
            console.log(data);
            $(this).next('.widget_content').html('test');
          }
        });
        break;
      }
    } else {
      // show current one
      $(this).next('.widget_content').slideToggle().parent().toggleClass('active');
    }
  });
});

Ajax call goes well, I get the desired data but the .next() function doesn't fill the div with widget_content class.

Any solutions or ideas about this?

Thank you.


Solution

  • You need backup this in child function

    $('.widget h3').on('click', function(){
        if( !$.trim($(this).next('.widget_content').html()) )
        {
            // if this widget don't have any data send ajax and load it
    
            var widget_id = $(this).attr('id');
            var _this = this; // backup this
            switch (widget_id) {
                case 'widget_lot':
                    $.ajax({
                        type:'POST',
                        url: '/dashboard/ajax_last_opened_tickets',
                        data:{},
                        success:function(data){
                            console.log(data);
                            $(_this).next('.widget_content').html('test'); //edit here
                        }
                    });
                    break;
            }
        }
        else {
            // show current one
            $(this).next('.widget_content').slideToggle().parent().toggleClass('active');
        }
    });