One possible solution is to copy the contents of the cell to keydown in a hidden field and calculate the value of this field:
$("table input").on("keydown", function(e) { $("#copy").text(this.value); var width = $("#copy").outerWidth(); console.log("w: " + width); var code = e.keyCode ? e.keyCode : e.which; if (width > 50 && code !== 8 && code !== 49) { return false; } });
I created a fiddle with this solution: http://jsfiddle.net/scaillerie/hnRjB/2/ .
It should be noted that the font family and font size must be the same in the input and in the div in order to have the correct value, which is the reason for the CSS rule:
* { font-family: arial; font-size: 1em; }
But instead of * you should limit your needs (e.g. table input, #copy ).
EDIT:
Just remember that with this code the user can enter only more input length, but you can add βlongβ to your copied character to check the width: http://jsfiddle.net/scaillerie/hnRjB/3/ .
source share