user1996496 user1996496 - 2 months ago 7
jQuery Question

How do I use a variable that I got through jQuery?

My code is like this and I'm trying to fill a form field with the result of the jQuery function. But it's not working. What am I doing wrong here? It logs the result to the console fine, including the hash and the array:

jQuery(document).ready(function() {
new GetBrowserVersion().get(function(result, components){
console.log(result); //a hash
console.log(components); //an array
});

var unique_id = result;

$('#unique_id').val(unique_id);
});


What I get is this:

Uncaught ReferenceError: result is not defined


Followed by the hash and array.

Answer

you are closing the function and the value is not available (in scope) to use to update the input:

jQuery(document).ready(function() {
    new GetBrowserVersion().get(function(result, components){
        console.log(result); //a hash
        console.log(components); //an array

        var unique_id = result;
        $('#unique_id').val(unique_id);
    });
});

Incidentally - you can use the argument directly in the function without creating the intermediate variable of result::

jQuery(document).ready(function() {
    new GetBrowserVersion().get(function(result, components){
        console.log(result); //a hash
        console.log(components); //an array

        $('#unique_id').val(result);
    });
});