18

How to check if is function on jquery, but function is in another .js file?

validation.js:

if ($.isFunction('payment')) {
    $('[data-numeric]').payment('restrictNumeric');
    $('.cc-number').payment('formatCardNumber');
    $('.cc-exp').payment('formatCardExpiry');
    $('.cc-cvc').payment('formatCardCVC');
}

this is false because func payments is in the payments.js .

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Haroldas
  • 964
  • 3
  • 9
  • 36
  • possible duplicate of [Javascript check if function exists](http://stackoverflow.com/questions/1042138/javascript-check-if-function-exists) – Liam May 13 '15 at 13:15
  • 1
    You want to check if jQuery `$` has the function defined. Ex. `$.myFunc` – Tushar May 13 '15 at 13:22
  • possible duplicate of http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type – ambodi May 13 '15 at 13:25
  • If it's specifically jQuery functions (though the fact that they are registered in jquery is pretty much irrelevant, a function is just a function regardless of where it is registered) there is also this [How to check jQuery plugin and functions exists?](http://stackoverflow.com/questions/5339876/how-to-check-jquery-plugin-and-functions-exists) – Liam May 13 '15 at 13:26

4 Answers4

36

Try like this

if (typeof payment === "function")
{
  // Do something
}
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
21

problem is solved. its works:

if ($.fn.payment) {
    //do something
}
Haroldas
  • 964
  • 3
  • 9
  • 36
9

Try to check like as follows,

 if (typeof payment !== 'undefined' && $.isFunction(payment)) {
    $('[data-numeric]').payment('restrictNumeric');
    $('.cc-number').payment('formatCardNumber');
    $('.cc-exp').payment('formatCardExpiry');
    $('.cc-cvc').payment('formatCardCVC');
 }
Shijin TR
  • 7,516
  • 10
  • 55
  • 122
  • `if is function on jquery, but function is in another .js file` – Tushar May 13 '15 at 13:18
  • 1
    files are irrelevant in js @Tushar. The "exists" is whether it is in the current scope of the window. The "files" simply add objects(functions) to the scope. What are you getting at? – Liam May 13 '15 at 13:19
  • @Liam He want to check if jQuery `$` has the function defined. Ex. $.myFunc – Tushar May 13 '15 at 13:21
4

You can check if a function exists using window

For example

var fn = window['NameOfTheFunction']; 
if(typeof fn === 'function') {
    doSomething();
}

If your function in payment.js is part of a self contained function, you need to set it to so the window object can "see" it by adding this in your self contained function:

window.NameOfTheFunction = NameOfTheFunction;
VVV
  • 7,563
  • 3
  • 34
  • 55