How do I see a variable from another script?

-4

I make it short. I have certain variables in script1 collected from html1 , and I want to see some from script2 when loading html2 . I tried using global variables, but I can not. I see them empty from script2 . I guess it's due to a question of scope that I do not know.

The user goes from html1 to html2 with a button. The variable of which I speak is, in particular, an option of a dropdown that I capture with JQuery and it is saved in a global variable. html1 and html2 each have their script. What I want to do is load html2 and show the option that the user chose in said dropdown located in html1 .

I tried doing this:

variableGlobal = funcionXqueRetornaOpciondeDropdown;

and then use the same variable in script2 , but I see it undefined. (Note that I refer to the two scripts in html2 at the end of the body)

script1

$(function(){
dropdownCaptura = function (dropdown, boton) {
        dropdown.on('click', 'li', function () {
            ciudad = $(this).text();
            if (boton.hasClass("btn-danger")) {
                boton.switchClass("btn-danger", "btn-primary", 0);
                $("#divDanger").fadeOut();
            }
            boton.html(ciudad);
            return ciudad;
        });
    };
});
ciudadOrigen = dropdownCaptura(dropdownOrigen1, btnDropdownOrigen1);

Dropdown capture works.

script2

$(function(){
    var ciudad = ciudadOrigen;
    console.log(ciudad);
});
    
asked by Gundwane 17.01.2017 в 22:50
source

2 answers

0

Dear, in this case I suggest you use the Storage location that all Internet browsers bring, such as Mozilla or Chrome. Below I leave an example.

How to use the localStorage

I hope it will be useful for you.

    
answered by 18.01.2017 в 04:23
0

The variables that you declare in javascript can have different scopes, these can be global or local, that declares a global variable does not want say that it can be accessed from another script, access to a variable declared in another script is impossible, but you can use query string to pass data from one tab to another the way to use it would be the following:

$(function(){
dropdownCaptura = function (dropdown, boton) {
        dropdown.on('click', 'li', function () {
            ciudad = $(this).text();
            if (boton.hasClass("btn-danger")) {
                boton.switchClass("btn-danger", "btn-primary", 0);
                $("#divDanger").fadeOut();
            }
            boton.html(ciudad);
            return ciudad;
        });
    };
});

ciudadOrigen = dropdownCaptura(dropdownOrigen1, btnDropdownOrigen1);
window.open('html2.html?ciudadOrigen='+ciudadOrigen , '_blank');

and to get the value of the variable in html2 you would use the following code

var urlParams = new URLSearchParams(window.location.search);
let ciudadOrigen = "";
if (urlParams.has("ciudadOrigen")) {
     ciudadOrigen = setSearchPanel(urlParams.get('ciudadOrigen'));
}
    
answered by 06.04.2018 в 07:15