html data- attribute as javascript parameter
The easiest way to get data-*
attributes is with element.getAttribute()
:
onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
DEMO: http://jsfiddle.net/pm6cH/
Although I would suggest just passing this
to fun()
, and getting the 3 attributes inside the fun
function:
onclick="fun(this);"
And then:
function fun(obj) {
var one = obj.getAttribute('data-uid'),
two = obj.getAttribute('data-name'),
three = obj.getAttribute('data-value');
}
DEMO: http://jsfiddle.net/pm6cH/1/
The new way to access them by property is with dataset
, but that isn't supported by all browsers. You'd get them like the following:
this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value
DEMO: http://jsfiddle.net/pm6cH/2/
Also note that in your HTML, there shouldn't be a comma here:
data-name="bbb",
References:
element.getAttribute()
: https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute.dataset
: https://developer.mozilla.org/en-US/docs/DOM/element.dataset.dataset
browser compatibility: http://caniuse.com/dataset
Pass javascript function as data-* attribute and execute
One way is to use eval()
jQuery(".container").on("click", "button.marker", function (e) {
var callback = jQuery(e.currentTarget).data("callback");
var x = eval(callback)
if (typeof x == 'function') {
x()
}
});
Demo: Fiddle
Note: Make sure it is safe in your environment, ie there is no possibility of script injection because of bad input from users
- Why is using the JavaScript eval function a bad idea?
- When is JavaScript's eval() not evil?
- eval() isn’t evil, just misunderstood
- Eval is Evil, Part One
Passing function with custom data attribute
You could do it as follows:
<div data-myattr="hello"></div>
function hello(){
console.log('hello');
}
function executeFunctionFromData(){
var d = 'hello' // Save `data-myattr` to d; (Obviously, this is just a hardcoded value as an example)
window[d](); // Execute the function.
}
This works because the function hello
is defined in the global scope, and as such, is a property of the window
object.
Use value from data attribute as url parameter
In modern browsers there is a much simpler built in URL API you can now use.
In button click handler check if the data attribute is set and has a value using data()
. If it is ... use URL.searchParams.set(key, value)
$('.button').click(function(){ var url = new URL(location.href), dataUrl = $(this).data('url'); if(dataUrl){ url.searchParams.set('someVar', dataUrl ); } console.log(url.href)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="button one">Click me</div><div class="button two" data-url="this-should-be-the-parameter">Click me</div>
Call a function inside a custom data-attr?
You could create a Function
from the data attribute:
// create
var funcStr = $('button').data('function');
var f = new Function(funcStr);
// invoke
f();
See MDN
How to set data attributes in HTML elements
HTML
<div id="mydiv" data-myval="10"></div>
JS
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
Demo
Reference
From the reference:
jQuery itself uses the
.data()
method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.
It should be noted that jQuery's data()
doesn't change the data
attribute in HTML.
So, if you need to change the data
attribute in HTML, you should use .attr()
instead.
HTML
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
jQuery:
alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
See this demo
How can I get the data-id attribute?
To get the contents of the attribute data-id
(like in <a data-id="123">link</a>
) you have to use
$(this).attr("data-id") // will return the string "123"
or .data()
(if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data-
must be lowercase, e.g. data-idNum
will not work, but data-idnum
will.
How to store arbitrary data for some HTML tags
Which version of HTML are you using?
In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.
<div data-internalid="1337"></div>
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.
Running function from attribute string
The very easiest way is to call eval()
like this:
$('select').change(function() {
var func = $(this).find('option:selected').attr('data-function');
eval(func);
});
Fiddle: http://jsfiddle.net/gywzb/4/
But the entire world agrees that this is a bad practice. As my favorite linter says, "eval() is evil." It opens you up to lots of nasty security holes (especially as you maintain the app and things change from how you initially wrote it), and the performance is abysmal anyway. Fortunately, there is a better way.
First, I'm going to break up your data attributes a little bit, so that instead of having one attribute that contains the function name and parameter, you'll have two attributes: one for the function name, and another for the parameter.
<select name="moduleGroup">
<option data-function="getListing" data-parameter="pages">Pages</option>
</select>
Second, we'll create a "class" that wraps your functions, like this:
var MyClass = function() {
}
MyClass.prototype = {
getListing: function(s) {
console.log(s);
}
};
Finally, here's how you use the above changes to call your function:
$('select').on('change', function() {
var func = $(this).find('option:selected').attr('data-function');
var param = $(this).find('option:selected').attr('data-parameter');
var myInstance = new MyClass();
var funcRef = myInstance[func];
funcRef.call(myInstance, param);
});
Here's the whole thing in a fiddle: http://jsfiddle.net/7CwH4/2/
The magic happens when you use the .call method to call your function. The .call()
method's first parameter is the object the function will see as its this
object. The next parameter to .call
is the first parameter to the function. (And if your function took more parameters, the third parameter to .call
would be the second parameter to the function, etc. See the MDN documentation for .call
if this is confusing.)
If you need to pass more complicated data than a string as the parameter, you can put it in the data-parameter
attribute as a JSON string, then use $.parseJSON to convert it into an object before passing the parameter to the function:
// If your data-parameter attribute contained a JSON string.
$('select').on('change', function() {
var func = $(this).find('option:selected').attr('data-function');
var param = $(this).find('option:selected').attr('data-parameter');
var paramObj = $.parseJSON(param);
var myInstance = new MyClass();
var funcRef = myInstance[func];
funcRef.call(myInstance, paramObj);
});
Related Topics
How to Make <Input Type="Date"> Supported on All Browsers? Any Alternatives
Prevent Orientation Change in iOS Safari
How to Move Table Row in Jquery
Using JavaScript to Change Website Language
Webpack File-Loader Outputs [Object Module]
Uncaught Typeerror: Cannot Read Property 'Top' of Undefined
What's the Difference Between Putting Script in Head and Body
JavaScript - .Innerhtml Changes Auto Close Tags
How to Keep the Menu State on Page Reload
How to Reorder Divs Using Flex Box
Reformat String Containing Date with JavaScript
How to Develop Desktop Apps Using HTML/Css/Javascript
Jquery - Sticky Header That Shrinks When Scrolling Down
Scrolltop Animation Without Jquery
Closing Websocket Correctly (Html5, JavaScript)
Remove Leading Zeros from a Number in JavaScript