0

I have a series of buttons that I'm appending a data ID to. I'm then trying to get the value of that button when it's clicked to push it into an array that eventually I'll read back out for applying some cookie values to.

I've piecemealed some bits together from other code examples. I feel that I'm really close, but I'm just not sure how to pull out the data ID to insert it into the array:

var z = [];
jQuery(document).ready(function($) {
 $(".btn").each(function(i) {
  i = i + 1;
 $(this).attr('data-id', ("btn_" + i));
  });
$('.btn').each(function() {
var btnData = $(this).data('id');
$(this).click(function(e) {
  z.push($(btnData).val());
  console.log(z);
   });
  });
});

Not sure what part I'm missing overall. Think it's something in the z.push($(btnData).val());.

1
  • 1
    Remove the line var btnData = $(this).data('id'); And modified this z.push($(btnData).val()); to z.push($(this).data('id')) Commented Feb 22, 2017 at 15:50

1 Answer 1

1

You directly need to push the value in array. Also you don't need each() to bind event handler.

var z = [];
jQuery(document).ready(function($) {
  $(".btn").attr('data-id', function(i) {
    return "btn_" + (i + 1);
  });
  $('.btn').click(function() {
    z.push($(this).data('id'));
    console.log(z);
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh, ok. Cool. Thanks! Yeah, I figured I was making this a little too complex than what it needed to be. Both yours and the comment above worked, but with yours it's much cleaner. Thanks again!

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.