I have a textbox
where the user can enter any number of characters, But I want its width to be increased dynamically with respect to the number of characters entered into it.
I have done a workaround shown below and it works partially, it will increase the width dynamically but not so precisely and will hide the first entered characters after a while because of my poor logic applied in it. I've just given a wild cutoff of 17 characters count to start the increment.
It should start the width increment only if the character count reaches the end of textbox.
UPDATE:
I am looking to make visible all the characters entered in the field, whereas in default the text box hides the leftmost characters.
HTML
<input type="text" id="txtbox" />
SCRIPT
$('#txtbox').keypress(function() {
var txtWidth = $(this).width();
var cs = $(this).val().length;
if(cs>17){
$(this).width(txtWidth+5);
}
});
You were using width field which is actually meant for type = image. You can get more info here. I have used size attribute which is used to set the size of input tag in pixels. When its 1 it can take 6 characters by default hence -6. Hope it helps.
Adding a simple inline code in onkeyUp should help
I have tried this code and it works fine.
Be sure to use mono space fonts in text box, otherwise the size attr. and number of characters won't match
A solution similar to @Tejas', but doesn't require the font to be mono-space:
The trick is to use
scrollWidth
, which gives us the total string length, even on single-line textboxes without a scrollbar: https://stackoverflow.com/a/9312727/1869660NOTE: I couldn't get this to work in IE, where
scrollWidth
always returned 2 for some reason..Some code:
JSFiddle example