1

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.

3
  • What is "size?" Length in characters? Height in pixels? Width in pixels? And why are there so many ; between the attributes of the input element? Commented Sep 5, 2012 at 12:19
  • @AaronDigulla The size attribut in html is the length in characters. Commented Sep 5, 2012 at 12:25
  • @Milos: See my answer given below. Commented Sep 5, 2012 at 12:43

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you A.K. In fact, I don't need to cach the keyup because I am populating the text input also with javascript.
As you type really long numbers, the first digit starts to go off to the left, not an ideal solution.
0

Remove the style attribute then try this:

$('input[type="text"]').keyup(function(){
  $(this).attr({width: 'auto', size: $(this).val().length});
});

Make sure no CSS styles are overriding the width. Got the answer from here: Dynamically resize input

2 Comments

Thank you for the answer but I would like to use only javascript and HTML, no JQuerry.
@Milos: See my answer with a javascript solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.