Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - Append text to end of text box dynamically with jQuery

I have the following input tag:

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

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';
});

but it didn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...