I'm trying to retrieve a server control in JavaScript. For testing purposes I am calling the JavaScript function from the page load event.
protected void Page_Load(object sender, EventArgs e){
ClientScript.RegisterClientScriptBlock(GetType(), "js", "confirmCallBack();", true);
}
And my JavaScript function is
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("PlaceHolderContent").FindControl("Button1").ClientID %>');
var b = document.getElementById('<%=Button1.ClientID%>');
}
my problem is that both a and b return null. Even when I view the page source the correct ClientID is returned.
I should add that I'm using master page.
Any ideas.
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!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">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With