Categories: Frontend Tech

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);

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

View Comments

  • Here's a better version. The main different is that the user will be unable to enter input past the maxlength limit

    Javascript Version:

    var enforceMaxLength = function(){
    $("[maxlength]").on("keydown", function(e){
    var $el = $(e.target);
    if( $el.attr("maxlength") < $el.val()){
    return false;
    }
    });
    };
    enforceMaxLength();

    Coffee version:

    enforceMaxlength ->
    $("[maxlength]").on "keydown", (e) ->
    $el = $(e.target)
    return false if $el.attr("maxlength") < $el.val()

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago