使用jQuery动态地将文本附加到文本框的末尾

时间:2012-11-06 01:09:30

标签: javascript jquery input

我有以下输入标记:

<input type="text" id="title" class="title" maxlength="20>

我需要在用户输入时将“day”附加到框中文本的末尾。这是如何用jQuery完成的?
我试过这个:

$('#title').on('keyup', function() {
this.value = this.value+' day';
});

但它不起作用。

1 个答案:

答案 0 :(得分:3)

使用jQuery在末尾附加文本,然后将插入符号移动到所需位置:

$('#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