Search code examples
javascriptinputcursor

show a specific symbol after the last letter in an input field


how can I show this symbol "|" after the last letter in an input field? Example: if the user enter any text in the input, lets assume he entered "abc" i want it to look like this in the input field "abc|" -to add (|) after the last character using javascript..

the idea is, I have a disabled input so there is no typing cursor appears in it, i want this symbol "|" to be like the typing cursor.


Solution

  • You want to do something like the following. You can use javascript's setInterval function to run at each chosen interval - in this case 500ms.

    Each time check if the placeholder === '|' and if so toggle it.

    See running code example below.

    var inpt = document.getElementById("input-box"),
    	ltr = document.getElementById("ltr");
    
    ltr.onclick = function () {
    inpt.value += "Q"
    }
    
    setInterval(function() {
       if (document.getElementById('input-box').placeholder === '|') {
           document.getElementById('input-box').placeholder = '';
       } else {
           document.getElementById('input-box').placeholder = '|';
       }
    
        if(document.getElementById('input-box').value.slice(-1) === 'Q'){
           document.getElementById('input-box').value += '|';
        } else if(document.getElementById('input-box').value.slice(-1) === '|') {
            document.getElementById('input-box').value = document.getElementById('input-box').value.slice(0, -1);
        }
    }, 500);
    <input type="text" id="input-box" disabled>
       <button id="ltr">Letter Q
    </button>