7

How to check if an HTML element already has autoNumeric initialized, so i won't initialize it again?

Initializing it twice results in all input numbers appearing twice.

if (// autonumeric not yet initialized) {
    var anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}

Edit: The reason to check is that autoNumeric might be previously initialized elsewhere, in another script with different autoNumericSettings and this script needs to respect the earlier set settings.

isherwood
  • 58,414
  • 16
  • 114
  • 157
lofihelsinki
  • 2,491
  • 2
  • 23
  • 35

3 Answers3

14

probably, you can use getAutoNumericElement(domElement) to check if an HTML element already has autoNumeric initialized

if (AutoNumeric.getAutoNumericElement(domElement) === null) {
    var anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}
4

You can indeed use AutoNumeric.getAutoNumericElement(domElement) as Aliaksandr mentioned to check if an element is returned, but the official way to check if a DOM element is already managed by AutoNumeric is this:

AutoNumeric.isManagedByAutoNumeric(domElementOrSelector);

So your code should be updated like so:

let anObject;
if (!AutoNumeric.isManagedByAutoNumeric(inputSel)) {
    // Also, no need to querySelector `inputSel` here:
    anObject = new AutoNumeric(inputSel, autoNumericSettings);
}

EDIT: Disclaimer; I'm the maintainer of AutoNumeric

Alex
  • 1,241
  • 13
  • 22
0

Don't declare the variable inside the if, do it outside and then just check.

var anObject = null;

if(anObject !== null) {
   anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}

If you post a bit more of your code I can make it better, I really don't know the structure of your complete code, but the principle is the same.

SrAxi
  • 19,787
  • 11
  • 46
  • 65
  • That's a good suggestion, but doesn't work here. The reason to check is that autoNumeric might be initialized elsewhere, in another script. I edited the question. – lofihelsinki Mar 07 '18 at 12:18