使用jQuery动态将文本追加到文本框的末尾 [英] Append text to end of text box dynamically with jQuery

查看:508
本文介绍了使用jQuery动态将文本追加到文本框的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入标签:

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

当用户键入内容时,我需要在框中的文本末尾附加"day". jQuery是如何完成的?
我已经尝试过了:

I need " day" to be appended to the end of the text in the box as the user types. How is this done with jQuery?
I've tried this:

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

但是没有用.

推荐答案

使用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();
    }
});

实时,有效的jsFiddle示例

这篇关于使用jQuery动态将文本追加到文本框的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆