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