0

I have a view dynamic variables that I would like to pass to an external javascript.

in the HTML I am setting a few hidden input fields, as such:

<input type=hidden id="varID" value="sourceID">

and then calling them in my external Javascript file as such:

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

When I check to see if there is anything in there, I always get an undefined. In my HTML, I am setting the hidden input field before I even al to load the external javascript file.

Any ideas of what I'm missing?

Murphy1976
  • 1,415
  • 8
  • 40
  • 88
  • 1
    Wait until the DOM is loaded in your external file before checking for the elements – Johan Apr 09 '15 at 14:40
  • use the onload() event from the html tag to call a function when the DOM is loaded. – jtb Apr 09 '15 at 14:44
  • [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Jonathan Lonowski Apr 09 '15 at 14:53
  • Possibly related: [Do DOM tree elements with ids become global variables?](http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) Using a global variable by the same identifier as the element's `id` may be clashing with the browser's own use of globals. – Jonathan Lonowski Apr 09 '15 at 15:13

2 Answers2

1

Try this in your external JavaScript.

$(document).ready(function() {    
    var varID = document.getElementById("varID").value;
});
rjmacarthy
  • 2,164
  • 1
  • 13
  • 22
tech-gayan
  • 1,373
  • 1
  • 10
  • 25
0

Try this:

window.onload = function () {
   var varID = document.getElementById("varID").value;
}

Basically, the JavaScript code will only run once the page has loaded.

rjmacarthy
  • 2,164
  • 1
  • 13
  • 22