0

I am trying to change my textbox's width according to textbox's value but it does not seems like working. Here is my aspx:

<asp:TextBox ID="TxtbSizeOzel" runat="server" CssClass="text-center"></asp:TextBox>$ 

I create an onKeyUp event for resizing method in codebehind:

TxtbSizeOzel.Attributes.Add("onKeyUp", "Expand(this)"); 

And lastly my javascript method:

function Expand(obj) { if (!obj.savesize) obj.savesize = obj.size; obj.size = Math.max(obj.savesize, obj.value.length); } 

I don't get any error but it just doesn't working.

1
  • are you using jquery? Commented Dec 7, 2015 at 11:23

2 Answers 2

2

UPDATED WITH CODE EXPLANATION:

here you go, the input will always be as long as its characters, whether you type, remove or give it a value before running the script: Demo here

//this is a plugin snippet (or function) to check if the element has //horizontal scrollbar $.fn.hasHorizontalScrollBar = function() { if (this[0].clientWidth < this[0].scrollWidth) { return true } else { return false } } //the end of plugin var originalWidth=$('.txt').width(); //we store the original width //(the width of the input at the page load) in a variable to use it as a //measurement in order to not let the input get smaller than this size //this function checks the width of `.txt` (the input) to see if it has //horizontal scrollbar or not, if it does then expands the width of the input to //the scroll size, else it checks to see if the width is added to the //original width, if so, removes one character (depending on the font size it'll //change - here it is 7 px) function changeWidth(){ if($('.txt').hasHorizontalScrollBar()){ $('.txt').width(document.getElementsByClassName('txt')[0].scrollWidth); } else if(originalWidth<$('.txt').width()){ $('.txt').width($('.txt').width()-7); } }; //end of the function changeWidth(); //run the function at page load, to give the input a size as wide as its // character's length $('.txt').keydown(changeWidth); //assign the function to the keydown event of the input //so whenever a character is added or removed the function will run again 
Sign up to request clarification or add additional context in comments.

Comments

0

Try using .width() property of JQuery. It supports the get and set operations for width manipulation of controls or elements in your HTML.

And you can try this if you want to go with JavaScript :

document.getElementById("yourControlId").style.width = "300px"; 

Hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.