Call a function onClick and passing it a value from the element's data-* attribute

Go To StackoverFlow.com

3

I have links like this:

<li><a href="#" data-value="Codes">Get codes</a></li>
<li><a href="#" data-value="Product">Get products</a></li>

How can I make it so that when I click on the link then a function gets called passing the value that's contained in data-value?

function refreshGrid(value) { }
2012-04-04 07:59
by Samantha J T Star
Java is not the same as JavaScript. For clarity make sure you get the distinction right - Wouter Lievens 2012-04-04 08:07


4

Try the following:

$('li > a[href="#"][data-value]').click(function (e) { // On click of all anchors with a data-value attribute and a href of # that are immediate children of li elements (nb this selector can be modifed to suit your needs)
  e.preventDefault(); // prevent the default (navigate to href)
  refreshGrid($(this).data('value')); // call your refreshGrid function with the value contained in the 'data-value' attribute
});
2012-04-04 08:03
by Rich O'Kelly


1

var linkValue = $("li a").attr("data-value");

Edit: Better example

$("li a").click(function () {
    var myDataValue = $(this).attr("data-value");
    refreshGrid(myDataValue);
});
2012-04-04 08:02
by sbhomra


1

here's a quick sample

$('ul').on('click','a[data-value]',function(){
    refreshGrid(this.getAttribute('data-value'));
    return false;
});
2012-04-04 08:07
by Joseph
Ads