Search code examples
javascripthtmljqueryonchangecontenteditable

Update value using jquery and contenteditable="true"


I have this HTML:

<tr role="row" class="odd">
    <td class="sorting_1">Deluxe Junior Suite</td>
          <td contenteditable="true" class="update_rate" data-id="46">0.00</td>
        </tr>

I want to update price using jquery when user change value in table cell so I write:

$('.update_rate').on('input', (e) => {

  var price = $(this).html();
    var id = $(this).data('id');

var data = {
                    _token: "{{ csrf_token() }}",
                    id: id,
                    price: price,
                    
    };
    console.log(data);
    $.ajax({
                    type: "POST",
                    url: '/update_rate',
                    dataType: "json",
                    data: data,
                    success: function (data)
                    {
                      if (data.status == '200') {
                            console.log('updated'); 
                          }                      
                    },
                    error: function(data)
                    {
                        console.log(data);
                    }
                });

  });

but I got an error:

jquery.min.js:2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of null

How to solve that? What is the problem?


Solution

  • You cannot use an arrow function, as they cannot have a this value bound to them. Use a normal function expression instead.

    $('.update_rate').on('input', function(e){
    
      var price = $(this).html();
        var id = $(this).data('id');
    
    var data = {
                        _token: "{{ csrf_token() }}",
                        id: id,
                        price: price,
                        
        };
        console.log(data);
        $.ajax({
                        type: "POST",
                        url: '/update_rate',
                        dataType: "json",
                        data: data,
                        success: function (data)
                        {
                          if (data.status == '200') {
                                console.log('updated'); 
                              }                      
                        },
                        error: function(data)
                        {
                            console.log(data);
                        }
                    });
    
      });