Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...