setting maxlength using javascript

后端 未结 7 1007
终归单人心
终归单人心 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 05:54

    The attribute you're looking for is maxlength, not max_length. See here.

    0 讨论(0)
  • 2021-01-05 06:00

    IE is case sensitive on setAttribute() and only "maxLength" works...

    var el=document.createElement('input'); el.setAttribute('maxLength',25);
    
    0 讨论(0)
  • 2021-01-05 06:08

    Don't forget though that if you are setting the maxlength via JavaScript, someone else could just as easily change the maxlength to whatever they like. You will still need to validate the submitted data on the server.

    0 讨论(0)
  • 2021-01-05 06:09

    All the answers here relies on keypress/paste events. Here is my solution using the input event:

    $('input').on('input', onInput);
    
    var inputValue = '';
    
    function onInput(e) {
        if(e.currentTarget.value.length > 30) {
            e.currentTarget.value = titleValue;
            return;
        }
    
        inputValue = e.currentTarget.value;
    }
    
    0 讨论(0)
  • 2021-01-05 06:09

    My code also print out the written/max characters, ignore that part.

    $("[maxlength]").bind("keyup focusin", function(){
        var maxkey = $(this).attr("maxlength");
        var length = $(this).val().length;
        var value = $(this).val();
        $(this).parent().find(".counter").text(length+"/"+maxkey);
        if (length > maxkey) $(this).val(value.substring(0, maxkey));
    }).bind("focusout", function(){$(this).parent().find(".counter").text("")});
    
    0 讨论(0)
  • 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);
        });
    });
    
    0 讨论(0)
提交回复
热议问题