Tuesday, January 27, 2009

Accessing ASP.Net Controls in JavaScript

Hey again,
Many times in our developement, we need some code to clear a form, or setting all the drop down lists to its zeroth indexes, or something related to that. At that time, writing a server side code using ajax is not a good practice, and doing it right away without ajax is the worst idea to deal with the situation.
Keeping that in mind, following code will help a lot, for example if we want to clear all the text boxes of the form we can write something like:


var inputElements = document.getElementsByTagName("input");
for (var count=0; count < inputElements.length; count++){
if(inputElements[count].type === "text"){
inputElements[count].value="";
}
}


Here is a list of input types that you can deal with like i have done in line 3 (inputElements[count].type)
  • For TextBox we have text
  • For DropDownList or html select, we have select
  • For RadioButton or RadioButton list, we have radio
  • For CheckBox or Checkboxlist, we have checkbox
  • For File Input, we have file

Note that all the types are in lower case. Regardless of they are asp.net controls or html controls, they will all became inputs at the clients end, so we can easily deal with them like above javascript. The only difference between them will be their ids. If any control is marked with runat=server attribute, its id will be generated by asp.net and that id can be accessible using control's ClientID property.

Hope this will help. Happy coding with js :)

No comments:

Post a Comment

Please add your valuable comments about this post if it helped you. Thanks

Popular Posts