views:

51

answers:

3

I had the following:

<script type="text/javascript">
var noteid = $('#noteid').val();
</script>
<input type="hidden" name="noteid" id="noteid" value="321">

This works great... but now I'm trying to move the JavaScript off the page into a linked JS file like so:

<script type="text/javascript" src="/js/note_beta.js"> </script>
<input type="hidden" name="noteid" id="noteid" value="321">

This ext JS file has the code: "var noteid = $('#noteid').val();" but it isn't working... Is there a trick to getting this to work when it isn't on the page itself?

Thanks

+8  A: 

Try wrapping your jQuery code in a (document).ready function, this ensures it doesn't run until the page has loaded and you don't run the risk of trying to reference elements before they are added to the DOM

So change:

var noteid = $('#noteid').val();

To this:

var noteid; // define it up here to ensure scope is done properly
$(document).ready(function() {
    noteid = $('#noteid').val();
});
Andrew G. Johnson
you beat me by 30 seconds :) +1 for being faster and more detailed.
John Duff
+1  A: 

try wrapping your code like this so it doesn't get run until the page is loaded

$(document).ready(function(){
  var noteid = $('#noteid').val();
});
John Duff
+1  A: 

In addition to the $(document).ready, don't ever give a JavaScript variable the same name as a named element (which usually comes up with inputs). It may not make a difference in this case, but it can lead to bugs. Check out this article on the scope chain down at the bottom for more info. This can easily bite you.

Edit: short version of the article is that named elements are added to the scope chain, so if the javascript is looking for a property .noteid, it will use input.noteid instead of window.noteid (window.noteid == var noteid when declared as a global variable.)

Isley Aardvark