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.
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.
3 Answers
Reset to default 14probably, 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);
}
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
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.