0

I have a webpage which utilizes javascript, and I have a .js file declared separately (I need it to be separately) Here's what's in the code:

$(document).ready(function() {
    $(document).on('click', 'input[name="rating"]', function() {
        var sf.gav = $(this).val();
        alert(sf.gav);
    });
});

However, no matter what I do or how I declare sf.gav, it is never saved so that I can use it later on the page (the code itself works and shows the number). It just says "undefined". Any advice?

Edit:: Thank you for your answers! I'm going to clarify a bit: I am using a game engine called "tyranobuilder" and it has its own variables. Only its own variables can be passed to another code that I need, specifically, a button that "submits" the information (the whole page is just a giant swarm of radio buttons). Therefore, I was looking for a way to get a value from jquery that I can then pass on to the button (first declaring "f.value = sf.gav"), which will in turn set in motion another script. After that, the initial value passed by the jquery can be forgotten. This button, and the declaration "f.value = sf.gav", are, obviously, at the end of the radio buttons. So far, even with your generous attempts at helping, nothing works..

8
  • Where do you 'need to use it later in the page'? This sounds like a scope problem. Commented Jul 19, 2018 at 15:16
  • Well, it's actually for an html game, so everywhere. It must be stored forever. Commented Jul 19, 2018 at 15:18
  • You are probably accessing it too soon in other parts of the code (like before the document is ready) Commented Jul 19, 2018 at 15:19
  • 2
    Note var sf.gav is invalid syntax you do not declare object properties with var / let Commented Jul 19, 2018 at 15:20
  • 1
    It's scoped to be only available inside the click event handler - move the var outside document.ready but still assign it inside docready/click handler: var gav ; $(function() { gav = 123 .. . You might still have issues if you access it too soon. Commented Jul 19, 2018 at 15:23

1 Answer 1

1

Your variable is private to $(document).on('click', 'input[name="rating"]', function() {}); event function. That's why you can't access it globally.

As I can understand you need to declare the variable globally like,

var sf = {gav: null}; // <--- like this.
$(document).ready(function() {
    $(document).on('click', 'input[name="rating"]', function() {
        sf.gav = $(this).val();
        alert(sf.gav);
    });
});

So you can access it anywhere.

Sign up to request clarification or add additional context in comments.

3 Comments

Note: global variables are mostly a bad idea, but this will solve the scoping issue.
@Liam yes of course!
Just highlighting a flaw in the general logic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.