Tutorial :How do access the contents of an HTML textbox on a page?


What is the recommended way of accessing the value of a textbox on a HTML page?


It depends on what you intend to do with the data. If you need to manipulate it on the client, the the jquery reference is appropriate. If you need to pass it to some business logic in your model, then the appropriate controller action is the place to do it. From the controller action you have access to the request object, which will have the text box's value. Additionally, if you've got a model object that corresponds to the text box's ID, you can use the UpdateModel function to map the values automatically.


If you want the contents of yout textbox on a submit then you should have a method in your controller which accepts the item as a parameter. For example, if your form has the textbox with id "myText" your controller should look something like:

[ActionName("WhateverYourShowFormActionIsCalled"), AcceptVerbs(HttpVerbs.Post)]  public ActionResult MyControllerAction(string myText)  {      //Do stuff with myText  }  


This has to be done on the client side. You could, however, send an AJAX request if the server requires the information. Examples in Scriptaculous/Prototype

function send() {      var val = $F('textBoxName'); // put own here      var url = "/ajax/textboxupdate"; // put own here      Ajax.Request ( url,          { method: 'get',            parameters: {'val':val},            onSuccess: new function(tr) { success(tr); }      });  }  

For two-way, use the tr.responseText parameter. (API ref)
ASP.NET AJAX could also be used - see the website.


Using JQuery you can do something like this:



In JavaScript, if you want to access to the contents of a textbox, you use the attribute value.

Example below ( type something inside any of the box and then click outside of it):

function logThis(elm){     console.log(elm.value);  }
<input type="text" onblur="logThis(this);" />  <textarea onblur="logThis(this);"></textarea>

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »