Science
Copyright © 2024 Jiri Kriz, www.nosco.ch
Snippet so7454116
Back to Overview

Having a permanent value in an input field while still being able to add text to it


<!DOCTYPE html>
<!-- http://stackoverflow.com/a/7454116 -->
<html>
<head>
<script type="text/javascript">
function getCaret(el) {
    var pos = -1;
    if (el.selectionStart) {
        pos = el.selectionStart;
    }
    else if (document.selection) {
        el.focus();         
        var r = document.selection.createRange();
        if (r != null) {
            var re = el.createTextRange();
            var rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);       
            pos = rc.text.length;
        }
    }  
    return pos;
}

function Input(id, immutableText) {
    this.el = document.getElementById(id);
    this.el.value = immutableText;
    this.immutableText = immutableText;
    this.el.onkeypress = keyPress(this);
}

function keyPress(el) {
    return function() {
        var self = el;
        return getCaret(self.el) >= self.immutableText.length;
    }
}

Input.prototype.getUserText = function() {
    return this.el.value.substring(this.immutableText.length);
};

</script>
</head>
 
<body>
<form>
<textarea id="ta"></textarea>
</form>
<script type="text/javascript">
var input = new Input("ta", "Enter your name: ");
var userText = input.getUserText();
</script>   
</body>
</html>