Monday, November 17, 2008

Javascript and Asp.net

1) Access Asp.net controls via Javascript:

-Javascript in .aspx page


document.getElementById('<%=NameOfControl.ClientID%>').PropertyName


-Javascript in .js file

First, you have to get the id of the control after the page is rendered (IE/FireFox->View->Page Source->Find the the control id)

document.getElementById('ctl00$ContentPlaceHolder1$txtFullName').focus();


2) Add Javascript function to asp.net controls:

NameOfControl.Attributes.Add("eventname","javascriptMethod") [vb]

NameOfControl.Attributes.Add("eventname","javascriptMethod") [C#]


Example: Validate empty value in a textbox.

-In aspx page add javascript function as following

<script type="javascript">
function IsEmpty()
{
if (document.getElementById('<%=textbox1.ClientID%>').value == "")
{
alert("Textbox is empty");
}
}
</script>


-In code behind, Add Following code on page_load

btnSubmit.Attributes.Add("onclick","IsEmpty()");

3)

No comments: