views:

91

answers:

2

I have a hidden input element that I am using as a counter to use to name more input elements generated by JavaScript. To get the value of the counter i use

parseInt($('#counter').val());

However I use this code snippet several times in my code, so I thought it would be good to put it in a function

function getCounter(){
   parseInt($('#counter').val());
}

this always returns undefined, while running just the code snippet returns the correct value. This happens in several ways that I tried defeining the function, as a function inside a $(function(){}), as a global function etc. How do I fix the scoping?

+6  A: 

Add "return" to your return statement :)

function getCounter(){
   return parseInt($('#counter').val());
}
James Skidmore
Wow. I feel silly. I guess I am too used to ruby right now.
Craig
Don't feel silly... it's always the little, assumed things that are impossible to catch. It just usually takes a fresh pair of eyes :)
James Skidmore
Only thing that is wrong with the solution is it needs to have the base included. return parseInt($('#counter').val(), 10); so you do not run into the Octal problem.
epascarello
Yeah, I missed the missing return too. I was just getting ready to add a comment asking for more code, thinking it was really a scoping problem....
Jonathan
+2  A: 

How about adding a return

function getCounter(){
   return parseInt($('#counter').val());
}
jitter