Limit text input to number of words

Posted by & filed under Javascript.

Javascript

function limitWords(id) {
	var maxWords=5;
	var d=document.getElementById(id);
	if ( d.value.split(' ').length > maxWords ) {
		t=d.value.substring(0,d.value.lastIndexOf(' '));
		d.value=t.substring(0,t.lastIndexOf(' ')+1);
	}
}
<textarea id='txt' rows="2" onkeyup="limitWords(this.id)"></textarea>

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Bitnami