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:
<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 totrim
;.replace(/\s+/g," ")
combines series of white spaces (including line feeds) into one (to bettersplit
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 tryonproperychange
first;- putting
function cnt()
andtextarea
/info
inwindow.onload
makes them "safe" inside the closure. They can't pollute the global namespace, and things in global namespace can not pollute them.