Reputation: 13
I have a text field with little underscores as (_________)
. How do I use JavaScript to make these dashes to be replaced by the input number upon typing? (48721____)
As I type, I want the underscore to be replaced with the number I type. How do I achieve this?
Upvotes: 0
Views: 208
Reputation: 16
You can do something like this:
const p = document.querySelector("p")
const amountOfDashes = 10
p.textContent = "_".padEnd(amountOfDashes, "_")
document.addEventListener("keydown", e => {
if(e.key === "Backspace") {
const pattern = /\d(?!\d)/;
if(!pattern.test(p.textContent)) return;
p.textContent = p.textContent.replace(pattern, "_");
return;
}
const val = parseInt(e.key);
if(isNaN(val)) return;
p.textContent = p.textContent.replace("_", val);
})
Tell me if this solves your problem.
Upvotes: 0
Reputation: 1
I think it's more of a CSS/HTML problem than a javascript problem.
For insertion you can use javascript like this
var input = document.querySelector('input');
input.addEventListener('keypress', function(){
var s = this.selectionStart;
this.value = this.value.substr(0, s) + this.value.substr(s + 1);
this.selectionEnd = s;
}, false);
Here is a working example https://codepen.io/jteck13/pen/RwYoeMp
Hope I could help
Upvotes: 0