1

Inside ajax success call, $(this).val() returns error;

I have a table where I am appending some values from database. I am wrapping my data using <div contenteditable = "true">. So, when I edit my table I want to get the changed/updated data.

So, in my ajax success call I am appending data to table and using $(selector).on("blur") method to try to get the updated data.

But, $(this).val() returns this error.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined at w.fn.init.val

$(document).ready(function() {
  $("select.option").change(function(e) {
    e.preventDefault();
    var value = $(this).children("option:selected").val();

    console.log(value);

    $.ajax({
      type: 'post',
      url: '/ajax',
      data: {
        value: value
      },
      success: function(result) {
        if (result.length === 0) {

        } else {
          console.log(result);

          let data = result;

          $.each(data, (index, item) => {
            $(".tableData").append(`<tr>
                    <td><div contenteditable = "true" class="edible">${item.st_id}</div></td>
                    <td><div contenteditable = "true" class="edible">${item.co1}</div></td>
                  </tr>`);
          })
          $(".edible").blur((e) => {
            e.preventDefault();

            console.log($(this).val())
          })
        }
      },
      error: function(err) {
        console.log(err)
      }
    });
  });
});

I understand the problem here is that when manually accessing $(this) it refers to the window itself rather than the element I am trying to access. But I have zero ideas how to access the edited/updated table data.

Adib Hasib
  • 92
  • 1
  • 2
  • 8
  • 2
    Protip: `edible` is a recipe for frustration with any other developer who touches your code. I'd go with `editable`. – isherwood Apr 17 '19 at 20:03
  • 3
    Arrow functions inherit `this` from the outer scope. In your case `this` will be tied to whatever `this` is when `success` is called. You can simply change your arrow function to a regular function to fix this problem (assuming that you want `this` to reference the `.edible` element). – Jake Holzinger Apr 17 '19 at 20:03

0 Answers0