Le Qs
Le Qs

Reputation: 805

Get data-* value on button click

I have this button

<button type="button" class="breakbtn btn btn-danger btn-cons btn-primary btn-block m-t-5" data-amounts="'+amounts+'" id="'+ti+'">Break</button>

and i am getting the value of id and data-amounts field after i click the button.

I can get the id using this code

var arr = event.target.id;

but this does not give the value

var initial = event.target.attributes.getNamedItem('data-amounts');

Here is a fiddle https://jsfiddle.net/8oLrxort/1/

Upvotes: 1

Views: 66

Answers (2)

David Thomas
David Thomas

Reputation: 253328

You have two options, either:

var initial = event.target.getAttribute('data-amounts');

Or:

var initial = event.target.dataset.amounts;

function withDataset(e) {
  console.log(e.target.dataset.amounts)
}

function withGetAttribute(e) {
  console.log(e.target.getAttribute('data-amounts'));
}

var one = document.getElementById('one'),
  two = document.getElementById('two');

one.addEventListener('click', withDataset);
two.addEventListener('click', withGetAttribute);
<button id="one" data-amounts="20">button 1</button>
<button id="two" data-amounts="400">button 2</button>

JS Fiddle demo.

Reference:

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115232

Use dataset property to get data-* attribute value

var initial = event.target.dataset.amounts;

$("button").click(function() {
  var arr = event.target.id;
  var id = arr;
  var initial = event.target.dataset.amounts;
  alert(arr);
  alert(initial);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="breakbtn btn btn-danger btn-cons btn-primary btn-block m-t-5" data-amounts="200" id="10">Break</button>

Upvotes: 1

Related Questions