Question

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

Was it helpful?

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.

OTHER TIPS

try to call cnt(w,x) on body onload event

onKeyUp triggers only on User Interaction.

If you load the side there is no Event KeyUp

so instead. Trigger it manually.

call cnt(document.brochure.freebrochureentryform,document.brochure.c) on your body manually (or onload)

function countWords(str) {
  let arr = str.split(' ');
  let count = 0;
  if(arr.length > 0){
    for (let i = 0; i< arr.length - 1; i++){
        let sentence = arr[0];
        let bool = true;
        for(let j = 0; j < sentence.length - 1; j++){
            let charcode = arr[i].charCodeAt(j);
            if((charcode > 64 && charcode < 91) || (charcode > 96 && charcode < 123)){
            bool = false;
            }
        }
        if(bool == true){
        count += 1;
        }
    }
  }
  return arr.length - count;
}

//function calling
countWords("he is a good programer, he won 865 competitions, but sometimes he dont. 
what do you think? all test-cases should pass. done-done?");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top