Search code examples
javascriptjquerynumber-formattingautonumeric.js

All methods return '.autoNumeric is not a function - Can't unformat numbers


I'm trying to get the raw values of input numbers formatted using autoNumeric, but can't because every method I try to do this with it returning '.autoNumeric is not a function' in the console.

$(document).ready(function() {

    new AutoNumeric('#input', 	AutoNumeric.getPredefinedOptions().numericPos.dotDecimalCharCommaSeparator);
    
    $('#input').on('keyup', function() {
    	$('#output').val($('#input').autoNumeric('getString'));
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-resource.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/4.0.3/autoNumeric.js"></script>

<input id="input" name="basicPayPerYearInput" type="text" value="123456.78" placeholder="0.00" class="currencyInput validate">

<input type="text" for="basicPayPerYearInput" id="output">

I can't even initialise inputs properly as written in most of the documentation using $(selector).autoNumeric(), so I've had to use the above 'new AutoNumeric', which is strangely also used in some documentation and is the only way that works:


Solution

  • It seems like you have been reading the documentation for the old API of AutoNumeric plugin. The plugin has been rewritten since them to be independent of jQuery, which means that .autoNumeric() is no longer a valid jQuery method.

    What you want to do is to store the AutoNumeric instance at runtime, and then simply use the getter method .getNumericString() on the instance to retrieve its string value:

    // Store instance
    var autoNumericInstance = new AutoNumeric('#input', AutoNumeric.getPredefinedOptions().numericPos.dotDecimalCharCommaSeparator);
    
    $('#input').on('keyup', function() {
        // Retrieve instance numeric string value
        $('#output').val(autoNumericInstance.getNumericString());
    });
    

    See proof-of-concept example here (or the updated fiddle):

    $(document).ready(function() {
    
        var autoNumericInstance = new AutoNumeric('#input', AutoNumeric.getPredefinedOptions().numericPos.dotDecimalCharCommaSeparator);
        
        $('#input').on('keyup', function() {
        	$('#output').val(autoNumericInstance.getNumericString());
        });
        
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/4.0.3/autoNumeric.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <input id="input" name="basicPayPerYearInput" type="text" value="123456.78" placeholder="0.00" class="currencyInput validate">
    
    <input type="text" for="basicPayPerYearInput" id="output">