I am trying to run a javascript function which is stored in a data attribute.
e.g.
<form data-success="test">...</form>
$('form').on('submit', function(e){
e.preventDefault();
var successFunction = $(this).data('success');
// Run success function here
});
function test(){
alert('run');
};
Is this possible or is there a better solution?
-
Please be a little bit clearer. I don't see any reason for this to happen given your example.Adrien Gorrell– Adrien Gorrell2013年09月19日 17:04:26 +00:00Commented Sep 19, 2013 at 17:04
-
eval("string function") is your friend but not recommended.Indi– Indi2013年09月19日 17:06:11 +00:00Commented Sep 19, 2013 at 17:06
1 Answer 1
Why are you storing application logic in your DOM in the first place? Why not store the function in your backing business logic in JavaScript?
This will prove to be a maintainability issue. Do not do this, instead store your functions in code and separate the logic of your presentation from what happens when it runs.
The simplest way is to classify your form and run a function accordingly, a better approach could be using something like an MV* pattern but let's not diverge. Here is the simplest solution I could think of without storing data attributes. This still does not do proper separation of concerns but it is a lot simpler than a data attibute.
...JavaScript with jQuery:
/now we select by class, and not just any form
$('.successForm').on('submit', function(e){
e.preventDefault();
test();
});
function test(){
alert('run');
};
THAT said, it can be done. eval($(this).data("success")) - please don't do this though, this bit is just here for completeness
10 Comments
window[$(this).data("success")]()