Search code examples
javascripthtmltextinput

HTML text input size


I have a text input created dynamically with javascript where I am putting some text with javascript also. I would like to make the text input size variable, dependent on the text length and with maximum width of 70%

For that, I am using:

'<input type="text" style="max-width:70%" name="affiliation"
 id="affiliation'+affiliation_id+'" value="'+article_affiliations[i].name+'"
 size='+article_affiliations[i].name.length+'/>'

Everything works fine when the text is longer than 68% but when not, the text input area is smaller than the text size.

For example, when the text size is 118, the textarea wil be only 106 characters length and I don't know why. Any help and suggestion will be highly appreciable.

Thank you.


Solution

  • Javascript:

    function incSize(event) {
       var size = event.value.length; 
       event.setAttribute("size", size);
       event.setAttribute("style", "width:auto")    
    }
    

    HTML:

    <input type="text" name="affiliation" onkeyup="incSize(this)" size="1" />​
    

    DEMO