Retrieve DIV value in ASP.NET using jQuery

This post is written by guest blogger Aamir Hasan

Although very simple to do, a lot of users ask how to retrieve the value of a DIV in ASP.NET using jQuery.

In this example, we will see how to retrieve and display the value of a div in an alert box, on the button click event.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Retrieve Value of DIV in ASP.NET</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
   1:  
   2:     
</script>
   1:  
   2:     <script type="text/javascript">
   3:         $(function() {
   4:             $('input[id$=btnClick]').click(function () {
   5:                 var divValue = $('#div1').html();
   6:                 alert(divValue);
   7:                 return false;
   8:             });
   9:         });
  10:     
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="div1">Aamir Hasan</div><br />
<asp:Button ID="btnClick" runat="server" Text="Click" />
</div>
</form>
</body>
</html>




The code is simple. There are just 2 things to keep in mind - To make it work in a MasterPage scenario and to avoid Client-Id issues, I have referenced button control as [id$=controlid] i.e. [id$=btnClick]. Moreover to prevent a postback on the button (btnClick) click event, the postback is prevented using return false.

OUTPUT

image

Aamir Hasan, is a Sr. Software Engineer and Technical Lead in a US based firm, having five years of experiences working in Software Design, Web Development, Consultancy and Training, using SQL Server and .NET Framework. He is an SEO professional too. He is capable of coordinating off-shore high level web development projects.






No comments: