aussiedan
aussiedan

Reputation: 341

How to call $(this) inside a function within a function?

I'm trying to add a delay() or setTimeout inside a function() that uses $(this). I want to use $(this) because this script is ran for each table row, so it has to target the same row. I can achieve this by using .closest() etc. However I'm just having difficulty calling $(this) inside a function within a function.

If I understand where I'm going wrong it's the fact that $(this) would be trying to get itself from setTimeout? If so how can I have it so I can use the same $(this) that I have been using?

Code in question:

setTimeout(function() {
 $(this).closest("td").next().find('.tabledit-save-button').click();
}, 2000)

Full Code:

<script>
$(document).ready(function () {
    $(document).ajaxComplete(function () {
        $('.tabledit-view-mode').on( 'click', function(e){
            $(this).closest("td").next().find('.tabledit-edit-button').click();
            $(this).find(".tabledit-input").val("completed");
            setTimeout(function() {
                $(this).closest("td").next().find('.tabledit-save-button').click();
            }, 2000)
        });
    });
});
</script>  

Thank you in advance.

Upvotes: 0

Views: 41

Answers (1)

Milan Chheda
Milan Chheda

Reputation: 8249

You can take that in a variable and use that variable instead of $(this), like below:

<script>
$(document).ready(function () {
    $(document).ajaxComplete(function () {
        $('.tabledit-view-mode').on( 'click', function(e){
            var current = $(this);
            current.closest("td").next().find('.tabledit-edit-button').click();
            current.find(".tabledit-input").val("completed");
            setTimeout(function() {
                current.closest("td").next().find('.tabledit-save-button').click();
            }, 2000)
        });
    });
});
</script>  

Upvotes: 1

Related Questions