I'm getting an error in Django Templates, with the event.preventDefault();

35 Views Asked by At

I'm made a dajngo website where if the product have a field with is_active = False, it gonna remove it from the basket in the shop.

So wrote this script in html file:

            {% if table.is_active %}
                    <div data-index="{{ table.id }}" class="table table-item">
                    <a href="{% url 'table_details' table.id %}" class="table-link">
                        <img class="table-img ib" src="{{ table.image.url }}" alt="">
                        <p class="title ib">{{ table.name }}</p>
                    </a>
                </div>
            {% else %}
                    <div data-index="{{ table.id }}" class="table table-item"></div>
                <script>
                    console.log("hello world 1")
                  $(document).ready(function (event) {
                  console.log("hello world 2")
                    event.preventDefault();
                    var tablid = $(this).data('index');
                    console.log(tablid)
                    $.ajax({
                      type: 'POST',
                      url: '{% url "basket:basket_delete" %}',
                      data: {
                        tableid: $(this).data('index'),
                        csrfmiddlewaretoken: "{{csrf_token}}",
                        action: 'post'
                      },
                      success: function (json) {
                        $('.table-item[data-index="' + tablid + '"]').remove();
                        document.getElementById("subtotal").innerHTML = json.subtotal;
                        document.getElementById("basket-qty").innerHTML = json.qty
                      },
                      error: function (xhr, errmsg, err) {}
                    });
                  })
            </script>
        {% endif %}

and in the console.log it gives me a warning and error with the same text,

# Uncaught TypeError: event.preventDefault is not a function
# at HTMLDocument.<anonymous> (basket/:116:27)
# at e (jquery-3.5.1.min.js:2:30005)
# at t (jquery-3.5.1.min.js:2:30307)

So what I did I tried to remove the line with event.preventDefault(), but then the data-index of the div stoped being used in the tablid varibale, and when I coneole.log(tablid), it show, undefined.

1

There are 1 best solutions below

0
mariodev On

In your example, this refers to the whole document, not the div element:

var tablid = $(this).data('index');

Instead, set the id for your element (eg id='foo') and use that:

var tablid = $('#foo').data('index');