Search code examples
javascriptformspageloadonkeyup

Javascript word count on page load not keyup


I have a little bit of javascript that counts the amount of words on a box. The javascript looks like this:

<script type="text/javascript">
    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;
        if (r > 60) {
            x.value='Please reduce the word count'; 
        }
    } 
</script>

and the form like this:

<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform" onKeyUp="cnt(this,document.brochure.c)"><?php echo $row['freebrochureentryform']; ?></textarea>

<label>Brocure Entry Word Count:</label>
<input type="text" name="c" value="0" size="20" onKeyUp="cnt(document.brochure.freebrochureentryform,this)" />

Basically the bottom input field shows the amount of words in the upper one. But it only does so when you click on the upper box "freebrochureentryform", but i want it to load the amount of words as soon as the page loads not when you click the box. I guess it is to do with

onKeyUp="cnt(document.brochure.freebrochureentryform,this)" 

But have no idea what to change it to.

(Btw way Brochure is the name of my form.)

Any help greatly appreciated.

Ian


Solution

  • You can call the cnt() function on window.onload event.

    And instead of listening to onkeyup event, you can listen to the more appropriate oninput (or onpropertychange for IE) event:

    JSFiddle

    <label>Free brochure from entry:</label>
    <textarea name="freebrochureentryform" id="freebrochureentryform">Lorem Text</textarea>
    <br />
    <label>Brocure Entry Word Count:</label>
    <input type="text" name="c" id="c" value="0" size="20" />
    
    window.onload=function(){
        function cnt(area,output){
            var txt=area.value.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ").split(" ");
            if(txt.length>10){
                output.value="Please delete some word";
            }else{
                output.value=txt.length;
            }
        }
        var textarea=document.getElementById("freebrochureentryform");
        var info=document.getElementById("c");
        if("addEventListener" in window){
            if("oninput" in textarea){
                textarea.addEventListener("input",function(){
                    cnt(textarea,info);
                },false);
            }else if("onpropertychange" in textarea){
                textarea.addEventListener("propertychange",function(e){
                    if((e||event).propertyName=="value"){
                        cnt(textarea,info);
                    }
                },false);
            }else{
                textarea.addEventListener("change",function(){
                    cnt(textarea,info);
                },false);
            }
        }else{
            textarea.attachEvent("onpropertychange",function(){
                if(event.propertyName=="value"){
                    cnt(textarea,info);
                }
            });
        }
        cnt(textarea,info);
    };
    

    Some instruction:

    • var txt=area.value
      • .replace(/^\s+|\s+$/g,"") means to trim;
      • .replace(/\s+/g," ") combines series of white spaces (including line feeds) into one (to better split without the need to iterate the splitted array);
      • .split(" ") split by white space (as you have already done).
    • oninput is introduced in IE9 but has some buggy behavior, so you may want to try onproperychange first;
    • putting function cnt() and textarea/info in window.onload makes them "safe" inside the closure. They can't pollute the global namespace, and things in global namespace can not pollute them.