5

What I am trying to achieve is to read value on click event and save it to an array. My code:

<a href='#' class="hotel" data-hotel-name='Holiday Inn'>Add to favourites</a>
var hotelName = [];    
$('.hotel').on('click', function(e){
    e.preventDefault();    
    hotelName.push( $(this).data('hotel-name') );
});    
console.log(hotelName.length);

The output is always 0. Could someone tell me what am I doing wrong, please?

1 Answer 1

5

Your logic is fine, you just need to read the length of the array after you modify it in the click handler:

var hotelName = [];    
$('.hotel').on('click', function(e){
    e.preventDefault();    
    hotelName.push( $(this).data('hotel-name') );
    console.log(hotelName.length); // < read the length of the amended array here
});

Working example

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, definitely. But you need to use them after the click event has placed some items in the array. Here's an example: jsfiddle.net/z3mpkcyc/3. Click the links to fill the array, then the button to see what's in the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.