2

I am creating buttons in jQuery dynamically. I need to add data attributes:

So I saw the answer here: Dynamically create buttons with Jquery

$(document).ready(function() {
  for(i = 1; i <=10; i++) {
     $('<button/>', {
        text: i, //set text 1 to 10
        id: 'btn_'+i,
        click: function () { alert('hi'); }
    });
  }
});

I am adding the data-attributes like this:

$(document).ready(function() {
  for(i = 1; i <=10; i++) {

   $('<button/>', {
        text: i, //set text 1 to 10
        id: 'btn_'+i,
        click: function () { alert('hi'); }
    }).attr('data-test', 1).attr('data-test2', 2);

  }
});

I was thinking that if I could do something similar to the way we add text and id attributes

Community
  • 1
  • 1
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119

1 Answers1

7

You can do that, but since the key contains - you need to pass the key as a string literal like

$(document).ready(function() {
  for (i = 1; i <= 10; i++) {

    $('<button/>', {
      text: i, //set text 1 to 10
      id: 'btn_' + i,
      click: function() {
        alert('hi: ' + $(this).attr('data-test'));
      },
      'data-test': 1
    }).appendTo('body');

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I know that this an older topic but I found this helpful and it will help others as it is the first link in google searches... You can do the same with regular attributes too... – Jesse Fender Aug 16 '18 at 15:19