Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery function cannot access global variable

I have two jquery click functions that sets and retrieves value from a javascript object.

var poly;

$( document ).ready(function() {
    //save drawing
    $("#save").click( function () {
        poly = new Polygon();
        poly.savedrawingaspoly(map.polygonevent);
        poly.tract = tract;
        poly.name = $('#polyname').val();
        console.log(poly);
    });

    $("#btnClear").click(function () {
        console.log(poly);
        //poly.clearplot();
    });
});

the console.log(poly); in $("#save").click works. the console.log(poly); in $("#btnClear").click returns undefined. How do I spread the scope of the variable, so the second one can see the variable? Thanks.

like image 883
arcee123 Avatar asked Sep 18 '26 16:09

arcee123


1 Answers

Use the window object to keep your variable in browser context. So the new code will look like:

$("#save").click( function () {
        poly = new Polygon();
        poly.savedrawingaspoly(map.polygonevent);
        poly.tract = tract;
        poly.name = $('#polyname').val();
        console.log(poly);

        window.poly = poly;
});

After implementing the code mentioned above; you can access poly variable through any function and also through your browser console.

like image 195
Bimal Avatar answered Sep 20 '26 07:09

Bimal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!