I’m working with event listeners on an asp.net TextBox and they do work fine until it loses focus. Once it does that it seems that event listeners are removed and they don’t fire at all as noted by the absence of logging in the console. My code should mask input text after 3rd character and ensure the cursor is positioned always at the end of text. Is there any way to reattach the listeners?
document.addEventListener("DOMContentLoaded", function() {
let node = document.getElementById('TxtAccountName');
let hidden = document.getElementById('HFAccName');
node.addEventListener('keydown', function(e) {
console.log("Fired the keydown event")
//compares the cursorPosition to the length of text
if (node.selectionStart !== node.value.length) {
e.preventDefault();
positionAtEndOfText();
}
});
node.addEventListener('keyup', function(e) {
console.log("Fired keyup event")
let text = node.value;
if (text.length > 3) {
node.value = text.substring(0, 3) + '*'.repeat(text.length - 3);
}
});
node.addEventListener('input', function() {
console.log("Fired input event")
if (node.selectionStart !== node.value.length) {
e.preventDefault();
positionAtEndOfText();
}
});
});
function positionAtEndOfText() {
let text = node.value;
node.focus();
if (node.setSelectionRange) {
node.setSelectionRange(text.length, text.length);
} else if (node.createTextRange) {
let range = node.createTextRange();
range.collapse(true)
range.moveEnd('character', value.length)
range.moveStart('character', value.length)
range.select()
}
}
<input id="TxtAccountName">
<input id="HFAccName">
I tried having a ‘focus’ event but apparently it didn’t work.