Issue
I have a input type text
<input type="text" id="txtid">
When i start typing text inside input, i should be able to get the lenght of the entered text.
This is what I tried:
document.getElementById("txtid").offsetWidth;
and
var test = document.getElementById("txtid");
var width = (test.clientWidth + 1) + "px";
These two does not give the width of the text entered
Basically what I want is:
For suppose input text width is 320px. I need the width of the entered text i.e 120px, which keeps on changing when I enter.
Solution
I see two ways.
First:
You can use a div with content editable instead input. Like this you can see the width of the div.
var elemDiv = document.getElementById('a');
elemDiv.onblur = function() {
console.log(elemDiv.clientWidth + 'px');
}
div {
width: auto;
display: inline-block;
}
<div id='a' contenteditable="plaintext-only">Test</div>
Note : Like @Leon Adler say, this way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.
Second:
Use an input type text and past the content into an invisible div. And you can see the width of the invisible div.
var elemDiv = document.getElementById('a'),
elemInput = document.getElementById('b');
elemInput.oninput = function() {
elemDiv.innerText = elemInput.value;
console.log(elemDiv.clientWidth + 'px');
}
.div {
width: auto;
display: inline-block;
visibility: hidden;
position: fixed;
overflow:auto;
}
<input id='b' type='text'>
<div id='a' class='div'></div>
Note : For this way, you must have the same font and font size on input and div tags.
Answered By - R3tep

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.