Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Posts
    341
    Thanks
    38
    Thanked 0 Times in 0 Posts

    Word counting in Iframe

    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:

    Code:
    <iframe id="iframe"></iframe>
    The paragraph to display the number of words:

    Code:
    <p id="num">0</p>
    The function in JavaScript for the word count:

    Code:
    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?

  • #2
    New Coder
    Join Date
    Oct 2012
    Location
    Basement
    Posts
    88
    Thanks
    9
    Thanked 0 Times in 0 Posts
    Hey there,

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

    Code:
    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:

    Code:
    <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/

  • #3
    Regular Coder
    Join Date
    Sep 2011
    Posts
    341
    Thanks
    38
    Thanked 0 Times in 0 Posts
    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...


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •