1

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?

2
  • Try, window[validate]() instead of introducing newValidate. Commented Sep 18, 2016 at 8:22
  • What are you expecting validate+"()"; to do, because I doubt it's what you are thinking it is (it's just a string). Commented Sep 18, 2016 at 8:22

2 Answers 2

5

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]()
Sign up to request clarification or add additional context in comments.

4 Comments

You don't need to use eval() here.
You don't need to, but it's one way to do it.
Yes it's a way you can do, but it's never a good idea to use eval that's subject to user input. Especially when it's not necessary and is likely slower.
But this isn't user input, it's an attribute from the HTML.
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.