Wednesday, November 9, 2011

Mvc Show/hide textbox as per Dropdown Value

Hi,

Here I explain how you can show hide text box as per dropdown value

Here in my controller I have taken one list for dropdown 1 to 5

 

   1:   public class HomeController : Controller
   2:      {
   3:          //
   4:          // GET: /Home/
   5:   
   6:          public ActionResult Index()
   7:          {
   8:              initilization();
   9:              return View();
  10:          }
  11:   
  12:          public void initilization()
  13:          {
  14:              ViewBag.bhavik= "Bhavik Test"; 
  15:              List<SelectListItem> LiList=new List<SelectListItem>();
  16:              AddItemInlist("One", 1, LiList,  false);
  17:              AddItemInlist("Two", 2, LiList, false);
  18:              AddItemInlist("Three", 3, LiList, true);
  19:              AddItemInlist("Founr", 4, LiList, false);
  20:              AddItemInlist("Fibe", 5, LiList, false);
  21:              ViewBag.DpList = new SelectList(LiList, "Value", "Text");  
  22:   
  23:          }
  24:   
  25:          public void AddItemInlist(string Key,Int32 value, List<SelectListItem> addtolist,bool IsSelected)
  26:          {
  27:              SelectListItem Li = new SelectListItem();
  28:              Li.Text = Key;
  29:              if (IsSelected)
  30:              {
  31:                  Li.Selected = true; 
  32:              }
  33:              Li.Value =value.ToString();
  34:              addtolist.Add(Li); 
  35:   
  36:          }
  37:   
  38:          [HttpPost]
  39:          public ActionResult Index(UserInformation u)
  40:          {
  41:              initilization();
  42:       
  43:              return View();
  44:          }
  45:   
  46:      }



 


Now in  View Page


 


   1:    @Html.DropDownList("dplist",(SelectList) ViewBag.DpList)    
   2:     @Html.TextBox("txtbox", "", new {style="display:none"})   


 


 


Java script


 


   1:  <script type="text/javascript">
   2:      $(document).ready(function () {
   3:   
   4:   
   5:   
   6:          $("#dplist").change(function () {
   7:              if (this.value == 2) {
   8:   
   9:                  $("#txtbox").attr('style', 'Display:inline');
  10:              }
  11:              else {
  12:                  $("#txtbox").attr('style', 'Display:none');
  13:              }
  14:          });
  15:   
  16:      }); 
  17:  </script>

 


Now textbox will show only when dropdown value is set to 2 else it will hide.


I hope this will help you  


[polldaddy poll=5657416]

3 comments: