PDA

View Full Version : Form field Limiter - modify to count words



ilazarus
04-20-2005, 04:21 AM
I have used the form field limiter, and it is great for counting characters, but does anyone know of a similar function which can limit the number of words you can enter in a field?

The original code is here: http://www.dynamicdrive.com/dynamicindex16/limitinput.htm

Thanks!

jscheuer1
04-20-2005, 07:50 AM
<script type="text/javascript">

/*
Form field Limiter script- By Dynamic Drive
For full source code and more DHTML scripts, visit http://www.dynamicdrive.com
This credit MUST stay intact for use
Modified to Limit the Number of Words
*/

var ns6=document.getElementById&&!document.all

function restrictinput(maxlength,e,placeholder){
if (window.event&&event.srcElement.value.replace(/[^ ]/g,'').length>=maxlength)
return false
else if (e.target&&e.target==eval(placeholder)&&e.target.value.replace(/[^ ]/g,'').length>=maxlength){
var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
if (pressedkey.test(String.fromCharCode(e.which)))
e.stopPropagation()
}
}

function countlimit(maxlength,e,placeholder){
var theform=eval(placeholder)
var lengthleft=maxlength-theform.value.replace(/[^ ]/g,'').length
var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
if (window.event||e.target&&e.target==eval(placeholder)){
if (lengthleft<0)
theform.value=theform.value.substring(0,maxlength)
placeholderobj.innerHTML=lengthleft
}
}


function displaylimit(thename, theid, thelimit){
var theform=theid!=""? document.getElementById(theid) : thename
var limit_text='<b><span id="'+theform.toString()+'">'+thelimit+'</span></b> words remaining on your input limit'
if (document.all||ns6)
document.write(limit_text)
if (document.all){
eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
}
else if (ns6){
document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true);
document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true);
}
}

</script>Usage is the same as the original.