Replace underscores on typing number input in JavaScript

162 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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