Le Qs Le Qs - 9 months ago 55
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/


You have two options, either:

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


var initial = event.target.dataset.amounts;

function withDataset(e) {

function withGetAttribute(e) {

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.