โดยใช้ <%= (ASP.NET Control ID).ClientID %>
เหตุผลที่ต้องใช้แบบนี้เนื่องจากใน ASP.NET นั้นหากเราใช้ Master Page ตัว Engine จะแปลง ID ของ ASP.NET Control ใหม่ เช่น อาจเป็น ID Master Page ตามด้วย ID ของ Control เราจึงใช้ตัวนี้เพื่อ get ID จริงหลังการ render webpage (ดู ID จริงโดยคลิกขวา เลือก view page source)
ที่จริงแล้วยังมีอีกวิธีในการ select Control คือใช้ attribute 'Class' แต่เอาไว้คราวหน้าจะมาเขียนให้ดูครับ
ดูโค้ดตัวอย่าง
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= Button1.ClientID %>').click(function () {
$('#<%= TextBox1.ClientID %>').val('Test Click');
alert('Alert Box');
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</p>
</div>
</form>
</body>
</html>
ผลลัพธ์เมื่อรันโปรแกรม
ไม่มีความเห็น