...

View Full Version : Word counting in Iframe



angelali
11-04-2012, 07:16 PM
I am making a rich text editor since 3 days.. Everything is fine except two things I want to add now. Of the things is a word count.

Well, I am using an IFrame. When the user will type, I want that simultaneously, the number of words he is typing is displayed. So here is code:

My iframe:


<iframe id="iframe"></iframe>

The paragraph to display the number of words:


<p id="num">0</p>

The function in JavaScript for the word count:


function wordcount () {
var chars = document.getElementById("iframe").contentWindow.document.body.innerHTML.length;
var regex = /\s+/gi;
var words = chars.trim().replace(regex, ' ').split(' ').length;
var answer = document.getElementById("num");
answer.innerHTML = wordcount();
};

Well, I want that each word the user is typing, the number of words is displyed, but it is not working.. Can someone help?

optimizer123
11-04-2012, 07:59 PM
Hey there,

You could make it a bit easier like this in the head section:


function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}
x.value=r;
}

and this in the body section:


<form name="myform">
<textarea rows="15" name="w" cols="45"
onkeyup="cnt(this,document.myform.c)"></textarea>
<br />Word Count: <input type="text" name="c" value="0" size="5"
onkeyup="cnt(document.myform.w,this)" />

I tried editing yours with no luck. Try the above instead if you keep struggling.

You can see it in action here:

http://jsbin.com/oyozej/1/

angelali
11-04-2012, 08:06 PM
I will try your code tomorrow..thank.. I will wait other answers as well.. By the way, instead of displaying the result in an input box, it will b better if it is in a paragraph...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum