Is there a way in JavaScript to get the maximum number of characters that can be displayed on an input field given a dynamic width (e.g. width = 100%)?
For example, if the value of an input field is "123456789" and due to width constraint, only "1234567" is displayable/visible, the maximum number of displayable characters is "7".
Example layout:
----------
|01234567|
----------
Current code: (I'm having problem with different font styles. Also, font-spacing is not yet considered. The code from getFontSize is from here.)
function countLetters()
{
var inputLong = document.getElementById('inputLong');
var fontSize = getFontSize(inputLong);
var fieldWidth = getWidth(inputLong);
console.log('Number of Visible Characters: ' + (fieldWidth / fontSize) );
}
function getFontSize(parentElement)
{
return Number(getComputedStyle(parentElement, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]);
}
function getWidth(parentElement)
{
return parentElement.offsetWidth;
}