AtT0mX
AtT0mX

Reputation: 23

How to pass data- value to jquery function

I have this HTML line with combination of TWIG code:

<a href="#" class="aaa" data-redirect="{{ path('rezervace_smazat', {'terminId':rezervaceTabulka[i]['id_rezervace']}) }}"> delete </a>

The line is a part of cycle, so in final result it can be multiple with different value of data-redirect attribute.

I need to pass the value of data-redirect to jquery function, but only a specific value when I click the hyper text link.

$(document).ready(function() {
        $('.aaa').on( "click", function(e) {
                e.preventDefault();
                $.confirm({
                        title: 'Smazat termín',
                        message: 'Opravdu chcete smazat tento termín?',
                        labelOk: 'Smazat',
                        labelCancel: 'Storno',
                        onOk: function() {
                                window.location.assign($(this).attr("data-redirect"));
                        }
                });
        });
});

The function works fine except of the line, where I need to redirect to different URL. I need to pass to the window.location.assign() function the specific value from data-redirect attribute.

Actually $(this).attr("data-redirect") does not pass the value from the attribute.

Thank you for help.

Upvotes: 0

Views: 1267

Answers (2)

jkris
jkris

Reputation: 6561

I believe is this is an issue. Sorry I just had to.

What I mean is

...
onOk: function() {
  window.location.assign($(this).attr("data-redirect"));
                           ^----- may not be referring to what you think it is.
}
...

A quick solution would be to change to to an arrow function like so

onOk: () => { window.location.assign($(this).attr("data-redirect")); }

If you need better support coverage you could assign the variable this as a work around like so

$(document).ready(function() {
        $('.aaa').on( "click", function(e) {
                var self = this; // <--- here 
                e.preventDefault();
                $.confirm({
                        title: 'Smazat termín',
                        message: 'Opravdu chcete smazat tento termín?',
                        labelOk: 'Smazat',
                        labelCancel: 'Storno',
                        onOk: function() {
                                window.location
                                      .assign($(self)
                                      .attr("data-redirect")); // <--- and here
                        }
                });
        });
});

Upvotes: 0

Undecided Dev
Undecided Dev

Reputation: 830

Try using. I hope this one helps.

$(this).data('redirect');

Upvotes: 1

Related Questions