简体   繁体   中英

Globally use the variable in jQuery

I am trying to use the logged in username as a global variable which can be passed to the internal forms, is there a way I can pass the logged in username variable to the other functions like below: Could anyone please help:

Fiddle

JavaScript:

    $(function() {

      function userLogin() {

        userName = $('#user').val();
        var password = $('#pass').val();
      }

     function requestDemo() {
        var userName = userName; // This should inherit the username from login function?
    }

});

You can just insert

var globalUsername = ''
var globalPass = '';

just underneath:

$(function() {

like this:

$(function() {
var globalUsername = ''
var globalPass = '';
...

or above, like this:

var globalUsername = ''
var globalPass = '';
$(function() {
...

After that, you can use these two variables on every place in your script.

We already have a global variable available to us. How about we simply create variables right on the jQuery object. Then, in our various functions, we can simply check if they exist, implement them if they don't, or reference them if they do?

Looking at your fiddle, this can also be done pretty painlessly -- simply have each function that needs access to a global namespace either create or reference it.

$(function() {
  $.bob_jsNS = $.bob_jsNS || {};

  var mainurl = 'http://localhost:9000';

  /* Login User */
  $("#submit-login").click(function() {

    userLogin();
  });

  function userLogin() {
    $.bob_jsNS.user = $.bob_jsNS.user || {};
    var myUser = $.bob_jsNS.user;

    myUser.userName = $('#user').val();
    var password = $('#pass').val();

    // var data = $("#login-user").serialize();

    var data = {
      "userName": myUser.userName
    }

    $('#sdlc-gif').show();

    // I simply reference the global namespace to get the userName.
    if (myUser.userName != '' && password != '') {
    // Removed for clarity. There was code here.
    }
  }


  function requestDemo() {
    /*****
     * Any time I need access to any part of the global namespace,
     *  I should first check that it's there -- and if not, create it.
     *  These first few lines happen on any function that will need to get
     *  or set global values or functions.
     ***/
    $.bob_jsNS = $.bob_jsNS || {};
    $.bob_jsNS.user = $.bob_jsNS.user || {};
    var myUser = $.bob_jsNS.user;
    // If we don't have a username, set it blank.
    //  May not be an issue, but it may break otherwise.
    var myUser.userName = myUser.userName || "";
    var myUser.first = ('#firstName').val();
    var myUser.last = ('#lastName').val();
    var myUser.title = ('#jobTitle').val();
    var myUser.email = ('#email').val();
    var myUser.comments = ('#comments').val();
    var myUser.app1 = ('#app1').val();
    var myUser.app2 = ('#app2').val();
    var myUser.app3 = ('#app3').val();

    var data = {
      "userName": myUser.userName,
      "firstName": myUser.first,
      "lastName": myUser.last,
      "jobTitle": myUser.title,
      "email": myUser.email,
      "comments": myUser.comments,
      "app1": myUser.app1,
      "app2": myUser.app2,
      "app3": myUser.app3
    }
    /***
     * More code was here, abbreviated for clarity.
     ***/ 
  }


  /* Provide feedback form */

  $("#submit-feed").click(function() {

    provideFeedback();
  });
  /* Provide Feedback */
  function provideFeedback() {
    // var data = $("#provide-feed").serialize();
    $.bob_jsNS = $.bob_jsNS || {}
    $.bob_jsNS.user = $.bob_jsNS.user || {};


    var userName = $.bob_jsNS.user.userName || "";
    var q1 = $("input[name='group1']:checked").val();
    var q2 = $("input[name='group2']:checked").val();
    var q3 = $("input[name='group3']:checked").val();
    var q4 = $("#ans4").val();
    var q5 = $("#ans5").val();

    var data = {
      "userName": userName,
      "q1": q1,
      "q2": q2,
      "q3": q3,
      "q4": q4,
      "q5": q5
    }
  }
});

I would suggest using either localStorage or sessionStorage depending on your needs for persistence. You can read more about the differences of the two here .

With the below method, you assign the username value to your web browsers local storage, and then retrieve that value from the local storage when you need it, and you don't necessarily have to worry so much about the scope of where your variables are placed.

$(function() {

      function userLogin() {

        localStorage.setItem('username', $('#user').val());
        var password = $('#pass').val();
      }

     function requestDemo() {
        var userName = localStorage.getItem('username');
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM