Code of the Day: Coffeescript + jQuery, enforce max length for all input elements

Enforce max length in all browsers since some browsers, IE8, don’t support maxlength for all input elements.

Coffeescript

# requires jQuery 1.6+ 
enforceMaxLength = ->
  $("[maxlength]").on "blur", ->
    $(@).val (index,val) -> 
      val.substring 0, $(@).attr("maxlength")

enforceMaxLength()

Javascript

// Generated by CoffeeScript 1.6.1
(function() {
  var enforceMaxLength;
 
  enforceMaxLength = function() {
    return $("[maxlength]").on("blur", function() {
      return $(this).val(function(index, val) {
        return val.substring(0, $(this).attr("maxlength"));
      });
    });
  };
 
  enforceMaxLength();
 
}).call(this);
(Page view Count: 27)