0

data("url") return undefined

$(document).ready(() => {
    $(".removeBtn").click((e) => {

        var $data_url = $(this).data("url");

        console.log($data_url); //It return undefined

        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.value) {
                window.location.href = $data_url;
            }
        })
    })
})
<button data-url="<?php echo base_url("product/deleteProduct/$product->id"); ?>" class="btn btn-outline btn-danger removeBtn">Remove</button>
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
Göktuğ Ozleyen
  • 121
  • 2
  • 14
  • Can you also add your html? – justDan Jun 11 '19 at 18:38
  • 2
    You're using an arrow function, which doesn't scope `this`. If you want `this` to refer to the clicked element, then you need to use a normal anonymous function - `$(".removeBtn").click( function() { ... } );` – Tyler Roper Jun 11 '19 at 18:43

1 Answers1

0

Apparently this does not reference the element you think it does.

(This is due to the arrow function, which doesn't scope this)

Instead you should use e.target here to get the clicked element

$(document).ready(() =>{ $(".removeBtn").click((e) =>{

    var $data_url = $(e.target).data("url");

    console.log($data_url); //It return undefined

})

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-url="something" class="btn btn-outline btn-danger removeBtn">Remove</button>

NOTE: the value of data-url is "something", so this snippet will just print the value e.g. "something" to the console

DigitalJedi
  • 1,577
  • 1
  • 10
  • 29