0

I'm trying to install a jQuery plugin for input masking. I've included the js file fine, and I try to initialize it per the docs:

<script src="autoNumeric.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $('#balance-input').keyup(function(){
        $('.stripe-button').attr('data-amount', $('#balance-input').val());
    });
    $('#balance-input').autoNumeric('init');
  });
</script>

The first keyup function works fine and is unrelated to the second function. In the console, I get an error that autoNumeric is undefined. Then I enter $('#balance-input').autoNumeric('init'); into the console and it works without a problem. It's inside document.ready and the plugin is included prior to the document.ready. What to do?

AKor
  • 8,550
  • 27
  • 82
  • 136
  • 5
    Could you explain how you're including your javascript files? Sounds like the file containing this is code is loaded/included before your plugin. – donnywals Oct 13 '15 at 14:38
  • 1
    Can you create a fiddle or snippet? – j08691 Oct 13 '15 at 14:38
  • 1
    fiddle would help to debug – J Santosh Oct 13 '15 at 14:38
  • 4
    Have you made sure that the plugin file is properly loaded before trying to run autoNumeric(); – Andrew Ice Oct 13 '15 at 14:39
  • It's loaded fine, that doesn't seem to be the issue. Updated my code. – AKor Oct 13 '15 at 14:42
  • Is this in Chrome? Have you tried any other browsers? I had an issue in chrome previously similar to this and had to add a timeout - replace directly your `$('#balance-input').autoNumeric` with `setTimeout(function() { $('#balance-input').autoNumeric("init"); }, 10);` (maybe tweak the 10, try 1000 as a start) – freedomn-m Oct 13 '15 at 15:36

2 Answers2

1

Even though you checked the load order, it really appears to be the problem. Everything has been loaded by the time you get to using the console. But during the script it runs as soon as it can. Document Ready waits for the DOM, but not necessarily all the scripts, depending on how they're loaded. Also, make sure only one core jQuery file is included (on some systems it might accidentally be included multiple times).

The next debugging step would be to set a breakpoint on the call to autoNumeric so that you can check what the state of the JavaScript load is at the time.

j08691
  • 204,283
  • 31
  • 260
  • 272
Jon Adams
  • 24,464
  • 18
  • 82
  • 120
0

You must add the script in different file(External javascript.js file), link it to your HTML and give
<body onload="functionname()">. What it will do is, run your script after the page loads.
For more refer this.

Yash
  • 369
  • 5
  • 18