Search code examples
javascriptjqueryajaxgetter-setter

Pass and update values from variable in .change function to global variable Jquery


I'm looking for a way to pass an array of values from var selectedId = [] in the .change(function{}) to the global var globalId = []. So every time the values changed in selectedId, I'd like to have a function like selectedId.update(globalId) or selectedId = globalId.update()to update the global id, but I don't know how to write this part. Eventually, I can use the up-to-date globalId in other change functions. Here's my code

$(function(){
    var globalId = [];

    $("#listbox1").change(function(){
        var selectedId =[];
        //get each selection
        $.each(selectedId , function (fIndex, fValue) {
            $.each(this.options, function (value, option) {
                if (this.selected) {
                    selectedId.push(option.value);
                }
            });
        });
        // send value to globalId 
        selectedId = globalId; // how to keep globalId up-to-date 
        // for everytime selectedId changes
        $.ajax({
            //....
            traditional: true, 
            data:{"// id in the controller": selectedId},
            success{...},
            error{...}
        });//end ajax

    });//end listbox1 change

    $("#listbox2").change(function(){
        var selectedId2 = [];
        // same each function to get selected <option>s as listbox1
        $.each{...
            $each{...
            };
        };
        $.ajax({
            //...
            data:{
                "//id1 in the controller": selectedId2, 
                "//id2 in the controller": globalId 
            },// this is the reason why I want to pass those values from listbox1  
            //to globalId so that I can use these two arrays in my controller function
            success{...},  
            error{}              
        });
    })//end listbox2 change
});//end ready

I will be sincerely appreciated if anyone have an idea to solve this question.

Thank you!

Kevin


Solution

  • You can do it this way.

    function GlobalIds(){
       var globalIds;
       return{
         getGlobalIds: function(){ return globalIds;},
         setGlobalIds: function(ids){ globalIds = ids}
        }
    }
    
    var globalIds = new GlobalIds();
    globalIds.setGlobalIds([1,2]);
    console.log(globalIds.getGlobalIds());
    globalIds.setGlobalIds([3,4]);
    console.log(globalIds.getGlobalIds());

    Also it seems you have done assignment in wrong way. Instead of

    // send value to globalId 
              selectedId = globalId; // how to keep globalId up-to-date 
                                    // for everytime selectedId changes
    

    It should be

     globalId = selectedId;