qwaz
qwaz

Reputation: 1305

limit number of characters displayed in live preview of input field

As I type text in the input field, the value is displayed live in p element: http://jsfiddle.net/HC9KD/

How can I display only as many as 25 first characters in the preview? I tried using some methods found on this site, but they did not seem to work for me.

text-overflow: ellipsis - will not do.

Appreciate any ideas.

HTML

<p id="preview"></p>
<input type="text" id="typedtext">

JavaScript

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('preview').innerHTML = this.value;
}

Upvotes: 0

Views: 472

Answers (4)

Xiphias
Xiphias

Reputation: 4716

Try this: http://jsfiddle.net/HC9KD/1/

Use slice() as documented here.

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('preview').innerHTML = this.value.slice(0,25);
}

Update:

I took the idea from ragatskynet and added the dots at the end if the number of characters of the input is longer than 25 characters. See the jsfiddle here: http://jsfiddle.net/HC9KD/7/

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('preview').innerHTML = this.value.slice(0,25) + function(x) {
        if(x.length > 25) { return " ..."} else {return ""};
    }(this.value);
}

Upvotes: 2

Vegeta
Vegeta

Reputation: 1317

Try this...

var wpcomment = document.getElementById('typedtext');
var count=1;
wpcomment.onkeyup = wpcomment.onkeypress = function(){
    if(count<=50){
         document.getElementById('preview').innerHTML = this.value;

     }
     count++;
 }

Upvotes: 0

justtal
justtal

Reputation: 800

http://jsfiddle.net/HC9KD/3/

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    if (document.getElementById('preview').innerText.length < 25) {
        document.getElementById('preview').innerHTML = this.value;
    }
}

Upvotes: 0

ragklaat
ragklaat

Reputation: 956

You can use substr().

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    if(this.value.length <= 25){
        document.getElementById('preview').innerHTML = this.value;    
    } else {
        document.getElementById('preview').innerHTML = this.value.substr(0,25) + "...";
    }
 }

http://jsfiddle.net/HC9KD/4/

Upvotes: 0

Related Questions