Using jQuery and ASP.NET

I’ve been using jQuery quite a lot lately in my ColdFusion apps. I’ve been working on a .NET site and yesterday I needed to throw a little jQuery into that site. I quickly found that ASP.NET poses one issue when using jQuery or simple Javascript in the situations where you are performing an operation on a named element. This relates specifically to using the ASP.NET controls, or any HTML control that has a runatserver command. As soon as you set runatserver=”true” on a control or HTML element, ASP.NET will rename that element when the page is loaded. For example, if I have a div element with an id attribute of “displayInfo”, ASP.NET will convert the ID into something like: ctl00MainContentdisplayInfo. As you can imagine this makes it difficult to use in some situations. But there is a very quick solution.

Microsoft has provided a simple ClientID variable that you can call that returns the correct ID of the control or HTML element. You just append .ClientID to the ID of your element. So in our example of above we would use displayInfo.ClientID anytime we needed to reference the displayInfo div in our jQuery or Javascript code.

Below is an example of using this with a little jQuery:

<code lang="javascript[lines]"><script type="text/javascript">
jQuery(document).ready(function($) { init(); })</script>

function init() { $("#").change(function() { slideForm($("#").val()) }); }

function slideForm(formVal) { if (formVal 'Detail') { $('#').slideDown(); $('#').slideUp(); $('#').slideUp(); } else if (formVal 'URL') { $('#').slideUp(); $('#').slideDown(); $('#').slideUp(); } else if (formVal == 'File') { $('#').slideUp(); $('#').slideUp(); $('#').slideDown(); } }

Comments

comments powered by Disqus