setting maxlength using javascript

后端 未结 7 1008
终归单人心
终归单人心 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:14

    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.

    0 讨论(0)
提交回复
热议问题