Link to home
Start Free TrialLog in
Avatar of PratikShah111
PratikShah111

asked on

Document getelementid are null

My HiddentFields are getting document.getElementById are not working as expected inside javascript in asp.net. Everytime I tried set a value for hidden field I get the following error

Uncaught TypeError : Cannot ready property 'value" of null


In the below code there is a javascript function loadfile().
This is the line where i am getting the error : document.getElementById("hAction").value = "";
if I move past that error the next step where i have to read/update value for a variable I am getting the above mentioned error. So looks like somewhere the variables are not getting set correctly

Here is my aspx code :

<%@ Page Language="C#"  MasterPageFile="~/MasterPage2.master" AutoEventWireup="true" CodeBehind="A.aspx.cs" Inherits="A" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<%@ MasterType VirtualPath="~/MasterPage2.master" %>

<asp:Content ID="Content2" ContentPlaceHolderID="CP1" runat="Server">


<meta http-equiv="Pragma" content="nocache">
<meta http-equiv="Expires" content="-1">
<title>Account Exception Upload</title>
<%--<script type="text/javascript" src="ccr_scripts.js"></script>--%>
<script type="text/javascript" src="/apps/jfunctions.js"></script>
<script type="text/javascript" src="/apps/jquery-1.11.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="/apps/commonStyles.css" />

<script type="text/javascript">

var timerID = -1;

function cancelProcessing()
{
	if (confirm("Are you sure you want to cancel processing of the previous file?"))
	{
		clearTimeout(timerID);
		document.getElementById("hAction").value = "cancel_processing";
		return true;
	}
	else
	{
		return false;
	}
}

function chkComplete()
{
	var chk_result = "";
	var u = "/apps/STAi/upload/chkComplete.ashx" +
			"?source_id=" + document.getElementById("hSource_id").value;
	$.ajax({
		async: false,
		type: "GET",
		url: encodeURI(u),
		dataType: "xml",
		success: function (xmlData)
		{
			try
			{
				$(xmlData).find('getResult').each(function (i)
				{
					chk_result = $(this).find('result').text();
				})
			}
			catch (e)
			{
				chk_result = "timeout";
			}
		},
		error: function (xhr, ajaxOptions, thrownError)
		{
			chk_result = xhr.status + "";
			if (chk_result == "404")
			{
				alert("File not found checking upload status.");
			}
		}
	});

	if (chk_result == "not_publishing")
	{
		submitPage("upload_done");
	}
	else if (chk_result == "publishing")
	{
		setCallBack();
	}
	else
	{
		submitPage("unknown_status");
	}
}

function loadFile()
{
    debugger;
	document.getElementById("haction").value = "";

	var fileName = LeftTrim(RightTrim(document.getElementById("fileUploader").value));
	if (fileName == "")
	{
		alert("Select a file to upload.");
		return false;
	}

	if (fileName.length > 200)
	{
		alert("The selected file's name exceeds the maximum allowed length of 200 characters.");
		return false;
	}

	var pos = fileName.length - 4;
	if (pos >= 0)
	{
		if (fileName.toLowerCase().substr(pos,4) != ".txt")
		{
			alert("Invalid file selected. File must be a tab delimited text file with name ending in \".txt\"");
			return false;
		}
	}
	else
	{
		alert("Invalid file selected. File must be a tab delimited text file with name ending in \".txt\"");
		return false;
	}


	if (!KeepAliveXML("reSubmit()"))
	{
		return false;
	}

	submitPage("upload_file");
	return false;
}

function reSubmit()
{
	document.getElementById("btnLoadFile").click();
}

function rowMouseOut(row, vWhich)
{
	var currentColor = row.style.backgroundColor.toLowerCase();
	if (currentColor != "pink" && currentColor != "lightsteelblue")
	{
		row.style.backgroundColor = (vWhich == "alternate") ? "#efebef" : "#ffffff";
	}
}

function rowMouseOver(row)
{
	// change the row color if it's not selected
	var currentColor = row.style.backgroundColor.toLowerCase();
	if (currentColor != "pink" && currentColor != "lightsteelblue")
	{
		row.style.backgroundColor = "#FFFF80";
	}
	row.style.cursor = "default";
}

function setCallBack()
{
	clearTimeout(timerID);
	timerID = setTimeout("chkComplete()", 15000);
}

function setPlsWaitPosition()
{
	//-- CENTER IN THE OPEN WINDOW --//
	var pnl = document.getElementById("pnlWait");
	var Hleft = window.document.body.offsetLeft + (window.document.body.offsetWidth / 2) - (pnl.offsetWidth / 2);
	var Htop = window.document.body.offsetTop + 175;
	pnl.style.pixelLeft = Hleft;
	pnl.style.posTop = Htop;
}

function showUploadErrorsRpt(upload_nbr)
{
	var url = "/apps/STAi/upload/file_validation_errors_rpt.aspx?upload_nbr=" + upload_nbr;
	window.open(encodeURI(url));
}

function submitPage(action)
{
    debugger;
	document.getElementById("hAction").value = action;
	document.forms[0].submit();
}

function window_onload()
{
	var action = document.getElementById("hAction").value;
	document.getElementById("hAction").value = "";

	if (action == "show_upload_alert")
	{
		var close_script = "";
		var beforeClose_script = "";
		var msg_id = document.getElementById("hMsgID").value;
		var url = "/apps/STAi/common/popup_msg_jquery.aspx?msg_id=" + msg_id;
		win = _openModalWindow("Message", encodeURI(url), 425, 225, false, "yes", close_script, beforeClose_script);
	}

	if (document.getElementById("pnlWait"))
	{
		setPlsWaitPosition();
		if (document.getElementById("tblData"))
		{
			document.getElementById("tblData").disabled = true;
		}
	}
}

function KeepAliveXML(script) {
    var return_val = true;
    $.ajax({
        async: false,
        type: "GET",
        url: $("#<%=hApp_path.ClientID%>").val() + "common/KeepAlive.ashx",
        dataType: "xml",
        success: function (xmlData) {
            try {
                $(xmlData).find('KeepAlive').each(function (i) {
                    if ($(this).find('Status').text() != "OK") {
                        return_val = false;
                    }
                })
            }
            catch (e) {
                return_val = false;
            }
        },
        error: function () {
            return_val = false;
        }
    });

    if (!return_val) {
        OpenReLogin(script);
        return false;
    }
    else {
        return true;
    }
    }

function OpenReLogin(script) {
    var iWidth, iHeight, iXpoint, iYpoint;
    iWidth = screen.width - 200;
    iHeight = screen.height - 200;

    if (iWidth > 900) iWidth = 900;
    iXpoint = (screen.width - iWidth) / 2;

    if (iHeight > 650) iHeight = 650;
    iYpoint = (screen.height - iHeight) * .1;

    reLoginScript = script;
    window.open($("#<%=hApp_path.ClientID%>").val() + "common/ReLogin.aspx?script=" + script, 'Login', 'toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=no,status=no,width=' + iWidth + ',height=' + iHeight + ',left=' + iXpoint + ',top=' + iYpoint);
}

function ReLogin() {
    if (reLoginScript != "") {
        eval(reLoginScript, 'JavaScript')
        reLoginScript = "";
    }
    }
    

</script>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
   
        <asp:Panel ID="pnlWait" Visible="false" runat="server" style="border:solid 2px gray; background-color:White; z-index:99; position:absolute; overflow:auto;">
	        <table style="margin:40px;">
		        <tr>
			        <td style="text-align:center; width:100%;">
				        <asp:Image ID="iWait" runat="server" ImageUrl="/apps/RSRcommon/images/wait24trans.gif" ImageAlign="Bottom" Style="position:relative; top:2px;" />
				        <asp:Label ID="lblWait" runat="server" CssClass="txtWarningLarge"></asp:Label>
			        </td>
		        </tr>
		        <tr>
			        <td style="padding-top:5px; text-align:right; vertical-align:bottom;">
				        <asp:LinkButton OnClientClick="javascript:return cancelProcessing()" CssClass="links" style="text-decoration:none;" runat="server">
					        Cancel Upload
				        </asp:LinkButton>
			        </td>
		        </tr>
	        </table>
        </asp:Panel>

        <asp:Panel ID="pnlStatus" Visible="false" runat="server">
	        <br />
	        <table style="width:650px; z-index:99; border:solid 2px gray; background-color:White; margin:auto;">
		        <tr>
			        <td style="padding:15px; width:20px; vertical-align:top;">
				        <asp:Image ID="imgCaution" ImageUrl="/apps/RSRcommon/images/caution.gif" runat="server" />
			        </td>
			        <td style="padding-top:15px; padding-bottom:15px; padding-right:15px; white-space:normal;">
				        <asp:Label ID="lblStatus" runat="server"></asp:Label>
			        </td>
		        </tr>
	        </table>
        </asp:Panel>
        <td style="width:100%; padding-right:10px; text-align:right;">
			                    <asp:Literal ID="lRequired" runat="server" EnableViewState="true" />
		                    </td>

        <asp:Panel ID="pnlUpload" runat="server">
        <br>
        <table style="border:ridge 1px; margin:auto;">
	        <tr>
		        <td style="padding:10px;">
			        <label style="font-weight:bold; font-size:10pt;">Select file to upload</label>
		        </td>
	        </tr>

	        <tr>
		        <td style="padding:10px;">
			        <asp:FileUpload ID="fileUploader" CssClass="buttonFlat" BackColor="white" Width="550px" runat="server" />
			        <asp:Button ID="btnLoadFile" CssClass="buttonFlat" Text="Upload File" OnClientClick="return loadFile()" Width="70px" runat="server" />
			        <asp:Image ID="imgHelp" ImageUrl="/apps/RSRcommon/images/helpr.gif" AlternateText="Help" runat="server" />
		        </td>
	        </tr>
        </table>
        </asp:Panel>
<br />
<br />

<asp:ObjectDataSource ID="dsTblData" runat="server"
	EnableCaching="false"
	SelectMethod="upload_history"
	TypeName="uploadsData"
	OnSelected="dsTblData_OnSelected">

	<SelectParameters>
		<asp:ControlParameter Name="timestamp" Type="string" ControlID="hTimestamp" PropertyName="Value" />
		<asp:ControlParameter Name="source_id" Type="string" ControlID="hSource_id" PropertyName="Value" />
		<asp:ControlParameter Name="nbr_periods_to_get" Type="Int32" ControlID="hPeriodsInHistory" PropertyName="Value" />
		<asp:Parameter Name="msg" Type="String" Direction="Output" />
		<asp:Parameter Name="row_count" Type="Int32" Direction="Output" />
	</SelectParameters>
</asp:ObjectDataSource>

<asp:GridView ID="tblData" runat="server" DataSourceID="dsTblData"
	AutoGenerateColumns="false"
	AllowPaging="true"
	AllowSorting="true"
	AlternatingRowStyle-BackColor="#efebef"
	CellPadding="3"
	EnableViewState="true"
	GridLines="None"
	HorizontalAlign="Center"
	OnDataBound="tblData_DataBound"
	OnRowDataBound="tblData_RowDataBound"
	PageSize="10"
	RowStyle-BackColor="#ffffff"
	ShowFooter="false">

	<pagersettings position="Top" Visible="true" />
	<PagerTemplate>
		<table ID="tblPager" style="width:100%">
			<tr>
				<td class="pageTitle">Upload History</td>
				<td style="text-align:right;">
					<asp:ImageButton ID="IBFirst" ToolTip="First" ImageUrl="/apps/RSRcommon/images/page_first.gif" CommandArgument="First" CommandName="Page" runat="server" />
					<asp:ImageButton ID="IBPrev" ToolTip="Previous" ImageUrl="/apps/RSRcommon/images/page_prev.gif" CommandArgument="Prev" CommandName="Page" runat="server" />
					Page <asp:DropDownList ID="ddlPages" OnSelectedIndexChanged="ddlPages_SelectedIndexChanged" AutoPostBack="True" runat="server"></asp:DropDownList> of <asp:Label ID="lblPageCount" runat="server"></asp:Label>
					<asp:ImageButton ID="IBNext" ToolTip="Next" ImageUrl="/apps/RSRcommon/images/page_next.gif" CommandArgument="Next" CommandName="Page" runat="server" />
					<asp:ImageButton ID="IBLast" ToolTip="Last" ImageUrl="/apps/RSRcommon/images/page_last.gif" CommandArgument="Last" CommandName="Page" runat="server" />
				</td>
			</tr>
		</table>
	</PagerTemplate>

	<HeaderStyle ForeColor="White" VerticalAlign="Bottom" />

	<Columns>
		<asp:BoundField DataField="upload_id" SortExpression="upload_id" HeaderText="Uploaded By" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="90px" />
		<asp:BoundField DataField="upload_dt" SortExpression="upload_dt" HeaderText="Uploaded On" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Width="135px" />
		<asp:BoundField DataField="rows_in_file" SortExpression="rows_in_file" HeaderText="Records In File" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right" HeaderStyle-Width="60px" DataFormatString="{0:N0}" />
		<asp:BoundField DataField="rows_passed" SortExpression="rows_passed" HeaderText="Records Passed" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right" HeaderStyle-Width="60px" DataFormatString="{0:N0}" />
		<asp:BoundField DataField="rows_errored" SortExpression="rows_errored" HeaderText="Records Failed" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right" HeaderStyle-Width="60px" DataFormatString="{0:N0}" />
		<asp:BoundField DataField="status_display" SortExpression="status_display" HeaderText="Result" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
		<asp:BoundField DataField="file_nm" SortExpression="file_nm" HeaderText="File" HeaderStyle-CssClass="gridHeader" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
        
	</Columns>
</asp:GridView>
<br />
<div style="width:100%; text-align:center;"><asp:Button ID="btnClose" CssClass="buttonFlat" Text="Close" OnClick="btnClose_Click" Width="70px" runat="server" /></div>

<asp:HiddenField ID="hAction" runat="server" />
<asp:HiddenField ID="hPeriodsInHistory" runat="server" />
<asp:HiddenField ID="hSource_id" runat="server" />
<asp:HiddenField ID="hTimestamp" runat="server" />
<asp:HiddenField ID="hMsgID" runat="server" />
<asp:HiddenField ID="hApp_path" runat="server" />


</asp:Content>

Open in new window

Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Try

var hActionID;
function window_onload() {
  hActionID = "<%= hAction.ClientID %>";

...

  document.getElementById(hActionID).value = "....";

 

Open in new window

Avatar of PratikShah111
PratikShah111

ASKER

that did not work
You need to view-source the page and see if the item in question actually has the ID you expect
Alternatively use a class which is not translated by ASP
Hi Michel, I have done view source and the item in question does not have any value. it is coming back as null and hence the error. Its as if those items are not getting initiated
in my code behind this is how I am trying to access the haction

string test = hAction.Value

and thats where haction is always coming back as ""
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial