[Solved] Append text to end of text box dynamically with jQuery


Use jQuery to append the text at the end, and then move the caret to the desired position:

$('#title').on('keyup', function(e) {
    // Ignore if backspace is pressed
    if(e.keyCode == 46){
       return false;
    }

    // Set the value based on the current value length
    // If it's longer than 3, "day" is already appended
    this.value = (this.value.length<3)?this.value+="day":this.value;

    // Move caret to the latest added character
    var caretPos = this.value.length-3;
     if(this.createTextRange) {
        var range = this.createTextRange();
        range.move('character', caretPos);
        range.select();
    }
    else {
        if(this.selectionStart) {
            this.focus();
            this.setSelectionRange(caretPos, caretPos);
        }
        else
            this.focus();
    }
});

Live, working jsFiddle example

3

solved Append text to end of text box dynamically with jQuery