Tom
Tom

Reputation: 25

Push this into an array onClick

I'm trying to push data into an array when I do an onClick event.

function clickCard() {
    $(document).on('click', '.card', function() {
        $(this).addClass('visible');

        var cardValue = $(this).attr('src');
        matchOrNot.push(cardValue);

    })
}

I'm trying to get the src of an image into the array and it needs to be that specific image (this) that I clicked on. Hope it makes sense.

When I try this I get 'undefined' of the variable matchOrNot.

This function works if I target a selector with a notation [0] but I want to get this.

Any idéas?

Upvotes: 0

Views: 1426

Answers (3)

ZorgoZ
ZorgoZ

Reputation: 3569

Something like this?

var A = []

  $('.card').on('click', e => {
      let $this = $(e.currentTarget)
      $this.addClass('visible')
      let cardValue = $this.attr('src');
      A.push(cardValue);
      
      console.log(A)
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card" src="https://dummyimage.com/100x100/000/fff" />
<img class="card" src="https://dummyimage.com/100x100/fff/000" />

Update:

After seeing your code I got the problem. Not matchOrNot is undefined, but the src attribute, as your current target is not the image but an outer div. You need to find the image within first:

$this.find('img').attr('src')

Upvotes: 1

Claudio Morales
Claudio Morales

Reputation: 1

You are trying to access the object src with the class .card when using $(this), the fastest solution would be to use a $('#id') to get the image src.

Upvotes: 0

Durgesh
Durgesh

Reputation: 205

The given click event i.e. click event on element with class 'card' should get registered when DOM is ready for interaction, and the place for that is $(document).ready() method.
Please wrap $(document).on inside ready event.
This should fix the issue.

Upvotes: 0

Related Questions