简体   繁体   中英

How to update global value after onchange call?

I run this function on a button click. Everytime I change smth and I store the value on a, I want it to store everytime on the global variable. But it doesnt.

function ChangeStuff() {
var localVariable;
$("#loc").change(function() {

  $("select option:selected").each(function() {

    Selected = $("#loc").find("option:selected").text();
  });

  arr.forEach(function(locItem) {
    if (Selected === locItem.s) {
      Selected1 = locItem._id;
    }

  });
  a = Selected1;
  //inside here shows correctly
  console.log(a);
  //apple //banana according to what i chose
}).change(); 
         }
     //here the global variable a is still 0;
       console.log(a);
       //0

 //i press continue to fire the function
//so everytime it changes I want it to update

this is where i fire the function

    <button  data-ver="1" id="Continue" onclick="ChangeStuf();">Continue</button>

       <select class="wide-control form-control default" id="locations" >
       <option>Apple</option>
        <option>Pear</option>
        <option>Banana</option>
        <option>Orange</option>
          </select>

when i assign the function onchange-"" on the select it gives me an infinite loop https://jsfiddle.net/x3s8pyam/1/

You aren't reassigning a new value to a at any point in the function. So, it's not going to change.

Think of a = selected1; as reading like "a 'is assigned' Selected1". And Selected1 = a; as the vice versa. That helps me :)

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