Jump to content
  • 0
Alison

Text box dynamically change for the inputted text

Question

3 answers to this question

Recommended Posts

  • 1

Hello Alison, 

If you have this element in the HTML: <input type="text" id="txtbox" />

you can apply the following JS code instead:


var txtBox = document.getElementById('txtbox');
document.addEventListener("keydown", function(event) { 
if(txtBox.value.length>20){ 
    if(event.keyCode!=8) //backspace check
          txtBox.style.width = (( txtBox.value.length+1) * 8) + 'px'; //extends the field by 1 character width when key is pressed
    else txtBox.style.width = (( txtBox.value.length-1) * 8) + 'px';} //shrinks the field by 1 character width when backspace is pressed
});

This code will dynamically adjust the width of your field depending on the number of characters. Feel free to adjust this to your needs if something is not meeting your expectations. 

Hope this helps! 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...