setting maxlength using javascript

后端 未结 7 1006
终归单人心
终归单人心 2021-01-05 05:14

I\'m trying to set the maxlength on input fields dynamically using JavaScript. Apparently that is a problem in IE, and I found part of the solution.

$(\"inpu         


        
7条回答
  •  清酒与你
    2021-01-05 06:10

    Because I had some trouble with the answer from @James I wrote sth that worked even when copy-pasting stuff, and especially when working with IE8 and down. My implementation uses jQuery and its live-events.

    jQuery(function () {
        $('body').on('keydown.maxlength_fix', 'textarea[maxlength]', function (e) {
            var $this = $(this);
            window.setTimeout(function () {
                var val = $this.val();
                var maxlength = $this.attr('maxlength');
                if (val.length > maxlength) {
                    $this.val(val.substr(0, maxlength));
                }
            }, 4);
        });
    });
    

提交回复
热议问题