1

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?

2 Answers 2

6

Add "return" to your return statement :)

function getCounter(){
   return parseInt($('#counter').val());
}
Sign up to request clarification or add additional context in comments.

4 Comments

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 :)
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.
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....
@Craig, you may want to look into CoffeeScript... It's Javascript for Ruby escapees :)
2

How about adding a return

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.