How to use a button's "data-" attribute to call a selected JavaScript function

tim peterson picture tim peterson · Oct 11, 2012 · Viewed 75.1k times · Source

I'm trying to set some data on my buttons such that it can be accessed onclick. I'm having no problem using JSON in a button's data attribute where the key value is a string. However, I can't figure out how to set the values to be a function.

What I'd like to happen upon clicking the button in this demo code is for the click event to call the function option1() which will alert the string "hello outside".

The error I'm getting is this:

Uncaught TypeError: Property 'option1' of object #<Object> is not a function

HTML (JSFiddle is here: http://jsfiddle.net/NDaEh/32/):

<button type='button' data-button='{"option1": "option1", "option2": 
"option2"}'>click1</button>

JS:

var data='hello outside';
var option1=function(data){
    alert(data)
}  

$('button').click(function(){
  //var data='hello inside';
  $(this).data('button').option1(data); // should alert 'hello outside'
});

Thoughts?

Answer

IvenMS picture IvenMS · Oct 11, 2012

Use the following code to get the values in your HTML:

$('button').click(function(){
  var data = $.parseJSON($(this).attr('data-button'));
  alert(data.option1)
});

This code is specifically for your requirement. By this way, you can store data in HTML and retrieve in JavaScript code.

Updated the JSFiddle code, working code is available at: http://jsfiddle.net/NDaEh/51/

EDIT:

Solution to call a function dynamically: http://jsfiddle.net/NDaEh/70/ HTML:

<button type='button' data-button='{"func": "func1"}'>click1</button>
<button type='button' data-button='{"func": "func2"}'>click2</button>

JS:

var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
};

$('button').click(function(){
  var data = $.parseJSON($(this).attr('data-button'));

  myFuncs[data.func]();
});