Result
maxlength属性は何かとアレなので文字数自体は制限せずに、予め設定した文字数を超過した際に警告文を出すようにする
jQuery
/** * Characters limit exceeded warning with a simple jQuery plugin * @copyright Copyright 2013-2015 Joan claret * @license MIT * @author Joan Claret Teruel <dpam23 at gmail dot com> * Licensed under The MIT License (MIT). * Copyright (c) Joan Claret Teruel <dpam23 at gmail dot com> */ ;(function($, document, window, undefined) { 'use strict'; var maxCharWarning = $.fn.maxCharWarning = function() { return this.each(function() { /*カスタムデータ属性等をセッティング*/ var el = $(this), maxLength = el.data('max-length'), warningContainerClass = el.data('max-length-warning-container'), warningContainer = $('.'+warningContainerClass), maxLengthMessage = el.data('max-length-warning') ; el.keyup(function() { /*文字数の取得とclassの付与*/ var length = el.val().length; if (length >= maxLength & warningContainer.is(':empty')){ warningContainer.html(maxLengthMessage); el.addClass('input-error'); } else if (length < maxLength & !(warningContainer.is(':empty'))) { warningContainer.html(''); el.removeClass('input-error'); } }); }); }; })(window.jQuery || window.$, document, window); if (typeof module !== 'undefined' && module.exports) { module.exports = maxCharWarning; }
$(document).ready(function(){ /*セレクタ指定*/ $('.js-max-char-warning').maxCharWarning(); });
html
<input class ="js-max-char-warning" placeholder="なにか書いてね" type="text" data-max-length-warning="10文字以内でおねがいします" data-max-length="10" data-max-length-warning-container="name" /> <span class="name"></span><!-- ここにエラーメッセージを表示 -->