0

I have a variable that I would like to use in another function but do not know how to call it correctly. External JS file:

<script>
function search ()
{
var subscriptionId = "";

if (document.getElementById('deleteyes').checked)
 {
  alert(subscriptionId);
 }
}
<script>

HTML file:

<script>
$(document).ready(function() { 
    $.getJSON(ravenUrl + '/indexes/dynamic/Subscriptions?query=Email%253A' + email, function(json) {
        subscriptions = json.Results;
        var html = '';
        for (var i in json.Results) {
            html += '<option value="' + i + '">Edit "' + json.Results[i].Name + '"</option>';
        }
        $('#subscriptionSelector').append(html);
    });

    $("#subscriptionSelector").change(function() { //alert('#forumSelector');
    var subscriptionIndex = $(this).val();
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    alert(subscriptionId);
    });
}
</script>



    <body>
<script type="text/javascript" src="externaljsfile.js"></script>
                                                        <p>create / edit subscription</p>
                                                            <select id="subscriptionSelector"><option selected="true" value="-1">Create new</option></select>
                                                <p>delete subscription</p>
     <div style="margin-left:35px;margin-top:6px;float:left;"><input type="radio" name="delete" id="deleteno" class="div1" checked />no</div>
    <div style="margin-left:35px;margin-top:6px;float:left;"><input type="radio" name="delete" id="deleteyes" class="div1"/>yes</div>

        </body>

The alert(subscriptionId) is generated correctly in the javascript from the html file but the alert in the external js file is obviously not generating the correct subscriptionId.

I realize that this might be a very simple problem but I am at a skill level where I can't even perform searches to find answers on problems related to javascript so please be patient. Thank you in advance.

1
  • Try defining var subscriptionId outside the search function, this should make the variable global. Else you could try window.subscriptionId Commented Oct 16, 2012 at 13:32

7 Answers 7

1

The most simple solution would be to declare subscriptionId in a global scope.

That means "outside of search()":

var subscriptionId = "";

function search ()
{

if (document.getElementById('deleteyes').checked)
 {
  alert(subscriptionId);
 }
}
subscriptionId = "what?";
search();
Sign up to request clarification or add additional context in comments.

3 Comments

Simple, yes, but a very bad idea
do you have any arguments to your opinion?
of course, I've posted an answer suggesting 3 alternatives that don't pollute the global object and added 1 argument against globals. I can give loads, if you want ;)
1

Put the variable declaration outside of a function var subscriptionId = ""; (Global Variable)

Then you could access this from any other function.

Comments

1

The issue here is one of scopes, you're (rightly) declaring subsriptionId in a function scope. As soon as that function returns, though, that variable is GC'ed (Garbage Collected).

As @GungFoo said, at first, you might think that declaring the variable globally, (and thus never have the var GC'ed) would fix things, and it would, at first. But pretty soon you'll pollute the global scope to such an extend that you'll run into issues. You could, inadvertently, change the value of a variable on which another function relies, for example. Just google a few articles on the matter, you'll soon find out why this isn't a good idea.

A few alternatives:

Assuming the "other function" is defined in the global scope, you could assign it a property:

function()
{//this declares and assigns subscriptionId
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    theOtherFunction.subscId = subscriptionId;//assign property
    alert(subscriptionId);
}
//the other one
function theOtherFunction()
{
    alert(theOtherFunction.subscId);//will alert the correct value
}

even simpler would be, simply to use the jQuery:

function theOtherFunction()
{
    var id = subscriptions[$("#subscriptionSelector").val()]["@metadata"]["@id"].substring(7);
    alert(id);//will work, too
}

The downside of the latter being that the DOM will be scanned on each call, to find that particular element ($("#subscriptionSelector")). To fix that, you can use a closure:

var theOtherFunction = (function(selector)//takes DOM element as argument
{
    return function()//this is the actual function
    {//thanks to closures, selector will not be GC'ed
        var id = subscriptions[selector.val()]["@metadata"]["@id"].substring(7);
        alert(id);//works like a charm
    };
})($("#subscriptionSelector"))//pass DOM element as argument

The last approach might seem a bit daunting at first, but spend some time reading up on IIFE, closures and scope wizardry. It's one of the best features of JS, very powerful, not that hard once you grasp the basic concepts, too!

Comments

0

The best solution would be to pass the subscriptionID over to the search function. If this is not possible, you would have to push it into a higher scope (e.g. global scope).

To make it globally available, change this:

var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);

To this:

window.subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);

Then it will be available in the external javascript as well.

Comments

0

subscriptionId is available in the functions scopes only

Move var subscriptionId = ""; bevore $(document) in the html file

Comments

0

Replace

<script>
function search ()
{
var subscriptionId = "";

with:

<script>
var subscriptionId = "";
function search ()
{

Comments

0

do :

$("#subscriptionSelector").on('change', function() { //alert('#forumSelector');
    var subscriptionIndex = this.value;
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    $(this).data('checked', subscriptionId); //store as data
    alert(subscriptionId);
});

and then :

function search () {
    var subscriptionId = $("#subscriptionSelector").data('checked');
    if ($('#deleteyes').prop('checked')) {
        alert(subscriptionId);
    }
}

That way the data would be stored on the element.

More about data() on jQuery : http://api.jquery.com/jQuery.data/

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.