1

I have a global variable called userValue. When the page loads, this value is finding the selected option and storing that options value. On load it would be storing default or null since the option is disabled. However, onchange (more options populate dynamically per site), I'm trying to store the value of the selected option globally so I can simply keep reusing the varialbe userValue. What I have below works properly when I include:

   userValue = $('#my_SiteUsers').find(':selected').val(); 

in the RefreshGroupList() function, but if i have to do that, doesn't that defeat the purpose of having a global variable? Right now, any change I make returns "default"

HTML:

 <select id="my_SiteUsers" style="width:200px;" onchange="RefreshGroupLists()">
        <option value='default' disabled="disabled">Select a user</option>
      </select>

JS:

  var user, userValue, userText, group, strHTMLSiteUsers, strHTMLSiteGroups, strHTMLAvailable, strHTMLAssigned, arrOptionsAssigned, arrGroups, arrUsers, intOpts, booMatch, booErr;

        $(document).ready(function(){ 
            user = $('#m

y_SiteUsers');
        userValue = $('#my_SiteUsers').find(':selected').val();
        userText = $('#my_SiteUsers').find(':selected').text();
        group = $('#my_SiteGroups');
        groupsAssigned = $("#my_SPGroupsAssigned").html("");
        groupAvailable = $("#my_SPGroupsAvailable").html("");
        userAssigned = $("#my_SPUsersAssigned").html("");
        userAvailable = $("#my_SPUsersAvailable").html("");

        $("button").click(function() { return false; });

        populateUsers();
            populateGroups();
        });


function RefreshGroupLists(){
            //Populate the Groups Assigned
          $().SPServices({
              operation: "GetGroupCollectionFromUser",
              userLoginName: userValue,
              async: true,
              completefunc: function(xData, Status) {
                $(xData.responseXML).find("errorstring").each(function() {
                  alert("User not found");
                  booErr = "true";
                  return;
                });
                $(xData.responseXML).find("Group").each(function() {
                  strHTMLAvailable += "<option value='" + $(this).attr("Name") + "'>" + $(this).attr("Name") + "</option>";
                  arrOptionsAssigned[intOpts] = $(this).attr("Name");
                  intOpts = intOpts + 1;
                });
                groupsAssigned.append(strHTMLAvailable);
              }
          });
}

JSFiddle

Batman
  • 5,563
  • 18
  • 79
  • 155
  • Where is that javascript? Inside script tag in the body or the head or an external js file? – UFL1138 Oct 01 '13 at 15:28
  • $ is not defined : you need to include jQuery in your fiddle :) – dezman Oct 01 '13 at 15:29
  • @watson I'm sorry, I posted only the relevant code in the jsfiddle, not the entire thing. My site has Jquery and the other framworks needed. – Batman Oct 01 '13 at 15:37
  • @UFL1138 it's in an external file – Batman Oct 01 '13 at 15:38
  • Does this help? http://stackoverflow.com/questions/944273/how-to-declare-a-global-variable-in-a-js-file – UFL1138 Oct 01 '13 at 16:05
  • I especially like the approach of the second answer where they recommend being explicit about attaching the variable to the window object. – UFL1138 Oct 01 '13 at 16:06
  • But they changed their answer indicating it wasn't necessary to attach it to the window object – Batman Oct 01 '13 at 16:07

2 Answers2

0

Since you intend that the value of $('#my_SiteUsers').find(':selected').val() changes assigning it as you did doesn't really help you. String values are copied by-value, you want a reference.

What you can do just keep a reference to the DOM element:

 userValueHolder = $('#my_SiteUsers').find(':selected')

and request the value when you need it with useuserValueHolder.val()

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • This will not work since the value of `userValueHolder` will not change if the selected user changes. What he wants is to magically track the selected option using a simple variable - that's not quite possible in javascript though it is possible to attach a handler to an onchange event for the selection and assign the currently selected option to the global variable - but he's already doing that. What he wants is to magically track the currently selected value without using onchange. – slebetman Oct 01 '13 at 15:38
0

I would do something like this.

// window.userValue = ''; // not necessary

$(document).ready(function(){
    var userValue;

    $('#my_SiteUsers').on('change', function(){
        RefreshGroupLists();
    });

    function RefreshGroupLists(){
        userValue = $('#my_SiteUsers').find(':selected').val();
        alert(userValue);
    }  
});

Its better to keep event handlers in your JS, not in your HTML, and to declare globals, though you shouldn't really need a global var for this, whatever you need to do with userValue can be put in RefreshGroupLists.

dezman
  • 18,087
  • 10
  • 53
  • 91
  • I plan on using the userValue in other functions though. So my only choice is to put userValue = $('#my_SiteUsers').find(':selected').val(); in every function I need it in? – Batman Oct 01 '13 at 15:39
  • I would declare it at the top of your doc ready function, but once your application reaches a certain level of complexity (maybe more than 400 lines) I would look into requireJS which enables you to scope your JS nicely. – dezman Oct 01 '13 at 15:41
  • This application will definitely reach +400 lines. It's already at 350ish. I'll take a look at requireJS, but for now I'll try what you posted. thanks – Batman Oct 01 '13 at 15:45
  • @Batman: No, you only need to include the code when the selection changes, which in this case is the `onchange` event. Your confusion stems from the fact that you also want to call RefreshGroupLists on change of selection value so you misunderstood the correlation of assigning the new value to userValue with calling RefreshGroupLists. – slebetman Oct 01 '13 at 15:46
  • To avoid confusion I think you should assign userValue in the onchange event handler but outside of (before) RefreshGroupLists. This will clearly indicate to you that setting userValue and calling RefreshGroupLists are two different things and if you need to call RefreshGroupLists outside of the onchange event then you don't need to assign the userValue. – slebetman Oct 01 '13 at 15:48
  • Oh okay, I think I get what you're saying (hopefully). Basically, before, I can refresh the group list, the userValue needs to change. So I need to attach an eventhandler that will change the userValue when the select has changed, then refreshGroupList will run using the new value. Did I get that right? – Batman Oct 01 '13 at 15:56