0

`

function init() {
  var a = 'output of my processing';
  alert('I am here'); // alert pops up
  document.getElementById("<%=hdnField.ClientID %>").value = a;
}
<head>
  <script src="../Scripts/myscripts.js"></script>
</head>

<body onload="init()">
  <asp:HiddenField ID="hdnField" runat="server" />
</body>

`I have a page with lot of javascript; I am trying to clean it up by moving the scripts to a script folder and reference the path; Seems to work fine, except when it encounters 'document.getelementbyid(controlname.id)'- it throws 'TypeError: Cannot read property 'value' of null'

I understand it is not able to find the control. Why does that happen? I thought the DOM is already built - what difference does moving the javascript to a path make to that anyway? Any ideas on how to make it work? I would really like javascript to be moved from the page.

user1191463
  • 395
  • 2
  • 5
  • 12

2 Answers2

1

This answer assumes your directory structure is correct.

Move your script tag to the bottom of the body, just before . Here is a good SO answer to this question, and here is another.

In addition, in general, it's bad practice to call a JavaScript function from inside HTML elements. If you're not using jQuery, you can add a "DOMContentLoaded" event listener to run the code. With jQuery, the standard $(document).ready() has been proven to work well. Or, if you simply put your script tag at the bottom of the , and place init(); at the end of your JS file, it will all run properly. This would be for a very simple application, but simplicity is sometimes the best.

Finally, for a sanity check, you could hard-code the ID in your init function. I don't know asp.net, but you might want to check the output of <%=hdnField.ClientID %>. Are you sure you're getting the correct ID?

Good luck.

Community
  • 1
  • 1
Paul
  • 1,056
  • 11
  • 18
1

You're using ASP.Net inline calls inside your JS. This couldn't work, for two reasons:

  1. It's likely you don't have your server configured to handle .js files using the ASP.Net processor.
  2. Even if you did, the processing of the .js would be completely separate to the hosting .aspx page; meaning hdnField would not be in scope.

You would be better off passing knowledge about the items on your page directly to the JavaScript:

JS:

function init(config) {
    var a = 'output of my processing';
    alert('I am here'); // alert pops up
    document.getElementById(config.hdnFieldID).value = a;
}

ASPX:

<head>
    <script src="../Scripts/myscripts.js"></script>
</head>

<body onload="init({ hdnFieldID: '<%= hdnField.ClientID %>' })">
    <asp:HiddenField ID="hdnField" runat="server" />
</body>

Hope that helps.

Paul
  • 1,502
  • 11
  • 19