javascriptjquerythis

Using this.id with JavaScript?


I am passing a DOM object after an onclick event occurs and I need to know the id of the element I've passed from the html. I've read about the this.id that exists in JavaScript but I cannot seem to utilize it correctly.

Here is my code in the function:

function clickFunction() {
    $(".tictactoe").on('click', function() {

        $(this).text("X");
        if (this.id == "upleft") {
            $('#upright').text("yes");
        }
    });
}

$(document).ready(function() {
    $('#playagain').hide();
    $('.tictactoe').on("click");

    clickFunction();

});

So I thought that my quick test, if successful, would present the word yes in the grid of a tic tac to bar in the upper right corner when I clicked the position on the left.

Perhaps there is something wrong with my comparison?

this.id == "upright"

The X's show up, indicating the rest of the code works, so it must be the comparison. Let me know your thoughts.


Solution

  • Pass the clickFunction in the click handler. Then remove the unnecessary click handler in the function.

    $(document).ready(function(){
        $('#playagain').hide();
        $('.tictactoe td').on("click", clickFunction);    //Added td click handler
    });
    
    function clickFunction()
    {
        $(this).text("X");
        if(this.id == "upleft")
        {
            $('#upright').text("yes");
        }
    }