最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - setting maxlength using javascript - Stack Overflow

programmeradmin0浏览0评论

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.

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");

function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

It works in Firefox, but not in IE for some reason. However, it works on input fields set like this:

<input type="text" max_length="25" onkeypress="return limitMe(event, this);"/>

But since the input fields are created dynamically, I can't do this... Any ideas?

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.

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");

function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

It works in Firefox, but not in IE for some reason. However, it works on input fields set like this:

<input type="text" max_length="25" onkeypress="return limitMe(event, this);"/>

But since the input fields are created dynamically, I can't do this... Any ideas?

Share Improve this question edited Mar 11, 2009 at 9:36 Ólafur Waage 70k22 gold badges146 silver badges199 bronze badges asked Mar 11, 2009 at 9:34 peirixpeirix 37.7k24 gold badges98 silver badges129 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 10

If you're using jQuery then why not make full use of its abstractions?

E.g.

Instead of:

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");
function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

Do this:

$('input#title').attr('maxLength','25').keypress(limitMe);

function limitMe(e) {
    if (e.keyCode == 8) { return true; }
    return this.value.length < $(this).attr("maxLength");
}

Edit: The reason it's not working in IE is probably because of how you attached the 'onKeyPress' handler, via setAttribute. - This isn't the proper way to register event handlers.

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

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

var el=document.createElement('input'); el.setAttribute('maxLength',25);

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.

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

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("")});

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)

  1. 暂无评论