简体   繁体   中英

Changing the value of a variable after an event

Right now in the below code the var selected doesn't change (it outputs the empty string i guess). I need you to help me change the selected variable so that the value should be the selected option all of the time (in the select element). I also want to be able to use that updated variable later in the code outside of the isSelected function.

var isSelected =  (function(){
  var selected = "";

    return {
        add : function(){
            $("select").on("change", function(){
                selected = $(this).val()
            })
        },
        output : function(){
            alert(selected)
        }
    }
})()

$("select").on("change", function(){
    isSelected.add();
    isSelected.output();
})

Thanks im trying my best to learn programing

 var isSelected = (function(){ var selected = ""; return { add : function(el){ selected = $(el).val(); }, output : function(){ alert(selected) } } })() $("select").on("change", function(e){ e.preventDefault() isSelected.add(this); isSelected.output(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="">Select combo</option> <option value="Value1">Text1</option> <option value="Value2">Text2</option> <option value="Value3">Text3</option> </select> 

Use this keyword to get current object. Please check the solution, hope this is what you need

The problem is binding to the change event in the add() function. You've already captured the change event, so when add() runs, it adds another change handler, which won't be triggered until the next change event fires.

The solution is to pass the selected value to add() as an argument.

I also want to be able to use that updated variable later in the code

Simply add another function, something like getSelected() which returns the value.

 var isSelected = (function(){ var selected = ""; return { add : function(value){ selected = value; }, output : function(){ alert(selected); }, getSelected : function(){ return selected; } } })(); $("select").on("change", function(){ isSelected.add(this.value); isSelected.output(); var selected = isSelected.getSelected(); console.log(selected); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option>One</option> <option>Two</option> <option>Three</option> </select> 

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