Question

While entering value in the textbox, when I enter value in between the entered value cursor moves automatically to the end of the value.

<!DOCTYPE html>
<html>
    <body>
        <script>
        function truncate(x) {
            if(x.value.length > 0) 
            {               
                x.value = x.value.replace(/^\s+/, '');
            }
        }
        </script>

        <input id="otherText" onkeyup="javascript:truncate(this);" maxlength="12" type="text"/>

    </body>
</html>

No correct solution

OTHER TIPS

<!DOCTYPE html>
<html>
<body>



<script>
function truncate(x){
var val = document.getElementById("otherText");

var inputTextValue = val.value;
if(inputTextValue.length>0) 
    { 

    val.value = '';

}
}
</script>
<input id="otherText" onkeyup="javascript:truncate(this);"   maxlength="12" type="text"/> </body>
</html>

Please note I don't know how to replace the string with specific regular expression. But the above code just replace with a empty string. You can modify as per your requirement.

try this

http://jsfiddle.net/DDQSU/2/

$(function() {

    function setCaretPosition(elemId, caretPos) {
        var elem = elemId
        if(elem != null) {
        if(elem.createTextRange) {
           var range = elem.createTextRange();
           range.move('character', caretPos);
           range.select();
        }
        else {
           if(elem.selectionStart) {
              elem.focus();
              elem.setSelectionRange(caretPos, caretPos);
           }
           else
              elem.focus();
        }
    }
}

$("#otherText").on("keyup", function(event){
                            var x = this,sel=x.selectionStart;
                            if(x.value.length > 0) 
                            {               
                                x.value = x.value.replace(/^\s+/g, '');
                            }
                            setCaretPosition(x,sel);
                        })
                 })

The solution was already there at Set keyboard caret position in html textbox

This question is a duplicate of Javascript, avoid cursor moving at textbox end

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top