Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
Try defining var subscriptionId outside the search function, this should make the variable global. Else you could try window.subscriptionId – Pilatus Oct 16 '12 at 13:32

7 Answers

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();
share|improve this answer
Simple, yes, but a very bad idea – Elias Van Ootegem Oct 16 '12 at 13:32
do you have any arguments to your opinion? – Gung Foo Oct 16 '12 at 13:33
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 ;) – Elias Van Ootegem Oct 16 '12 at 13:47

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

Then you could access this from any other function.

share|improve this answer

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!

share|improve this answer
Wow, thank you. I appreciate your input! – Niko Oct 16 '12 at 13:51

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.

share|improve this answer
Thank you, works quite nicely. – Niko Oct 16 '12 at 13:51

subscriptionId is available in the functions scopes only

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

share|improve this answer

Replace

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

with:

<script>
var subscriptionId = "";
function search ()
{
share|improve this answer

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/

share|improve this answer
Thank you, appreciate it! – Niko Oct 16 '12 at 13:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.