Dynamically Change Size of Textbox in Web API Using jQuery

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.

  1. 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.

      Select MVC4 Web Application

    • From the "MVC4 Project" window select "Web API".

      Select Web API

    • Click on the "OK" button.
  2. Now add the following code in the index.cshtml file:
    • In the "Solution Explorer".
    • Expand the "Home" folder.
    • Then select the "index.cshtml" file.

      Select Index View

Add the following code:

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
  5. <script type="text/javascript">  
  6.     function IncreaseTextboxSize() {  
  7.         var textsize = $('#txtwidth').val();  
  8.         $("#txtname").css("width", textsize);  
  9.         $("#message").html("Currently textbox Size is " + textsize + "px.");  
  10.     }  
  11. </script>  
  12. <h2>  
  13.     Dynamically change TextBox Size</h2>  
  14. <br />  
  15. Type TextBox Width: <input type="text" id="txtwidth" />px   
  16. <input type="button" value="Change Size" onclick="javascript: IncreaseTextboxSize();" /><br />  
  17. <br />  
  18. <br />  
  19. @Html.TextBox("TextBoxName"""new { @id = "txtname" })  
  20. <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:

  1. <script type="text/javascript">  
  2.     function IncreaseTextboxSize() {  
  3.         var textsize = $('#txtwidth').val();  
  4.         $("#txtname").css("width", textsize);  
  5.         $("#message").html("Currently textbox Size is " + textsize + "px.");  
  6.     }  
  7. </script> 

Now execute the application; the output will be as:

Index View


Increase the size of the TextBox:

Increase size of Textbox

Decrease the size of the TextBox:

Decrease size of Textbox


Similar Articles