Le Qs Le Qs - 4 months ago 25
jQuery Question

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/

Answer

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:

Comments