Wednesday, April 15, 2009

Enforce max length on textareas and textfields

This is a mixin that can be used to enforce the maximum content length of any textarea or text input. It uses javascript to chop off any character that exceeds the given maxlength.

Usage:

<textarea t:type="textarea" t:mixins="maxlength" max="100"></textarea>

MaxLength.java

/**
 * Enforces maxlength on a textfield or a textarea
 * 
 * @author Inge
 *
 */
@IncludeJavaScriptLibrary("MaxLength.js")
public class MaxLength {
  
  @InjectContainer
  private ClientElement container;
  
  @Parameter(required=true)
  private int max;
  
  @Parameter("true")
  private boolean displayCounter;
  
  @Environmental
  private RenderSupport renderSupport;
  
  void afterRender(MarkupWriter writer) {
    String id = container.getClientId();
    String counterId = id + "-counter";
    writer.element("div", "id", counterId + "-container");
    if (!displayCounter) {
      writer.attributes("style", "display: none");
    }
    writer.element("input", "type", "text", "id", counterId, "disabled", "disabled", "size", "3");    
    writer.end();
    writer.end();
    renderSupport.addScript("new MaxLength('%s', '%s', %s)", id, counterId, max);
  }
}


 MaxLenght.js





var MaxLength = Class.create();
MaxLength.prototype = {
	initialize: function(id, counterId, max) {
		this.max = max;
		this.element = $(id);
		this.element.observe('keyup', this.keyup.bindAsEventListener(this));
		this.counterElement = $(counterId);
		this.updateCounter();		
	},
	keyup: function(event) {
		if (this.element.value.length > this.max) {
			this.element.value = this.element.value.substring(0, this.max);
		}
		this.updateCounter();
	},
	updateCounter: function() {
		var currentLength = this.element.value.length;
		this.counterElement.value = (this.max - currentLength);
	}
}

No comments:

Post a Comment