Introduction
This article describes how to change the size of a TextBox at run time using jQuery. The TextBox size can be changed in pixels.
The following is the example.
- Create a web API application as in the following:
- Start Visual Studio 2012.
- From the start window select "Installed" -> "Visual C#" -> "Web".
- Select "ASP.NET MVC4 Web Application" and click on the "OK" button.
- From the "MVC4 Project" window select "Web API".
- Click on the "OK" button.
- Now add the following code in the index.cshtml file:
- In the "Solution Explorer".
- Expand the "Home" folder.
- Then select the "index.cshtml" file.
Add the following code:
- @{
- ViewBag.Title = "Index";
- }
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
- <script type="text/javascript">
- function IncreaseTextboxSize() {
- var textsize = $('#txtwidth').val();
- $("#txtname").css("width", textsize);
- $("#message").html("Currently textbox Size is " + textsize + "px.");
- }
- </script>
- <h2>
- Dynamically change TextBox Size</h2>
- <br />
- Type TextBox Width: <input type="text" id="txtwidth" />px
- <input type="button" value="Change Size" onclick="javascript: IncreaseTextboxSize();" /><br />
- <br />
- <br />
- @Html.TextBox("TextBoxName", "", new { @id = "txtname" })
- <div id="message" style="color:blue;font-size:20px;"></div>
In the code above the following code is used to change the size of TextBox:
- <script type="text/javascript">
- function IncreaseTextboxSize() {
- var textsize = $('#txtwidth').val();
- $("#txtname").css("width", textsize);
- $("#message").html("Currently textbox Size is " + textsize + "px.");
- }
- </script>
Now execute the application; the output will be as:
Increase the size of the TextBox:
Decrease the size of the TextBox: