EHerman
EHerman

Reputation: 1903

$(this) doesnt work within a function?

I have a function that is called when a button is clicked. I want to traverse down the dom to get to a hidden input field that has some stored data that I need to access.

Button

<button class="btn btn-small btn-danger delete-video-btn" onclick="delete_video()"><span class="icon-remove"><i> </i></span>Delete Video</button>   


JavaScript

function delete_video() {
    alert('delete video is running');
    var thisUniqueID = jQuery(this).parent().parent().parent().find('input[name="uniqueVideoID"]').val();
    alert(thisUniqueID);
    //alert("Are you sure you want to delete this video?");
}


But as it sits now, using (this) within my jquery doesn't work as intended. If I were to set it up like this it would work, but that doesn't work well with the code I have set up.

This works, but not what I need

jQuery('.delete-vide-btn').click(function() {
  var thisUniqueID = jQuery(this).parent().parent().parent().find('input[name="uniqueVideoID"]').val();
  alert(thisUniqueID);
})      

How can I get it to find the correct element and store the data, when the function runs, and not using the .click function?

Upvotes: 2

Views: 88

Answers (3)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

You can do this :

onclick="delete_video.call(this)"

and change nothing to your code.

Here an example

Upvotes: 4

Ankit Agrawal
Ankit Agrawal

Reputation: 6124

Try this function  

  function delete_video() {
        alert('delete video is running');
        var thisUniqueID = jQuery('.delete-vide-btn').parent().parent().parent().find('input[name="uniqueVideoID"]').val();
        alert(thisUniqueID);
        //alert("Are you sure you want to delete this video?");
    }

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You need to pass the context of "this" to the function:

onclick="delete_video(this)"

then....

function delete_video(something) {
    $this = something;
    ...
}

Upvotes: 2

Related Questions