Reputation: 3444
I am trying to create a function in jQuery based on the data attr.
<input type="text" name="name" id="name" data-validate="validatename" />
$("#name").blur(function(){
var validate = $(this).attr("data-validate");
var newvalidate = validate+"()";
newvalidate;
});
function validatename(){
alert("success");
}
Debugging gives the value of newvalidate
as validatename()
but the function doesn't run. How can i make this work?
Upvotes: 1
Views: 305
Reputation: 782653
Creating a string that ends with ()
won't cause the function to be executed. To execute a string as if it's Javascript code, you need to call eval()
:
$("#name").blur(function(){
var validate = $(this).attr("data-validate");
var newvalidate = validate+"()";
eval(newvalidate);
});
function validatename(){
alert("success");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="name" data-validate="validatename" />
You could also just look up the name in the global scape to get the function itself and call it.
window[validate]()
Upvotes: 5
Reputation: 21575
That's because it's not a function, newvalidate
is just the string with the value of "validatename()"
and nothing more. To run a global function which you have the name as a string you can do window[validate]()
:
<input type="text" name="name" id="name" data-validate="validatename" />
$("#name").blur(function(){
var validate = $(this).attr("data-validate");
window[validate]();
});
function validatename(){
alert("success");
}
Upvotes: 3