Somename Somename - 2 months ago 9
jQuery Question

Creating function with jquery data attribute

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?

Answer

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"); 
}
Comments