Reputation: 1305
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
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
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
Reputation: 800
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
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) + "...";
}
}
Upvotes: 0