1

I have a function which inside contains a

 .on('change', function(){})

Prior to this onchange function I have a variable. Within the onchange function the variable gets updated when the user clicks a button however I cannot update the variable outside the onchange function and receive a not defined error.

How can I get the new values once the on change is triggered outside the function as seen in the code below

/* Ready Function */
$(function(){
    $('.container').each(function(){
        let date = new Form($(this));
    });
});
const Form = function(this$obj){
    this.$obj = this$obj;
    this.init();
};
Form.prototype.init = function init(){
  this.checkFunction();
  this.clickFunction();
};
Form.prototype.checkFunction = function checkFunction(){
  let formField = this.$obj.find('.input_field_01');
  let today = '01 / 28 / 1979';
 
  formField.on('change', function(){
    if (formField != ''){ 
      console.log('date found');
      newValue = formField.val();
      console.log(newValue);
    }else {
      console.log('no date found');
      newValue = mm + '/' + dd + '/' + yyyy;
      console.log(newValue);
    }
    console.log('outside if statement');
    console.log(newValue);
  });
  console.log('date outside change function');
  // this is where things break newValue not defined if uncommented
  //today = newValue;
  console.log(today);
}

// working
Form.prototype.clickFunction = function clickFunction(){
  let findField = this.$obj.find('.input_field_01');
  let button = this.$obj.find('.date_updater');
  let text = '02 / 19 / 1981'
  button.on('click',function(){
    findField.val(text).change();
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <form>
    <input type="hidden" class="input_field_01" name="input_field_01" value="">
    <span class="input_value_01"></span>
  </form>
  <br>
  <button class="date_updater" type="button">
    Change Date
  </button>
</div>
DigitalDesigner
  • 274
  • 2
  • 19
  • The first loop in the script doesn't practically do anything with `date`, and setting a new object reference to the same variable in the loop doesn't make much sense, even if the variable was declared in the outer scope. You've to get familiar with [how variable scope works](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) in JavaScript. – Teemu Jan 24 '23 at 06:32
  • Why do you wish to update it outside your change function? Can't you not just update it at the end of it.? – Carsten Løvbo Andersen Jan 24 '23 at 06:33
  • later after the change function I will be using the value in a litepicker as such need to get the values outside the onchange. I just left out all the extra code as it wasn't needed. if you feel it would help I can add it in. – DigitalDesigner Jan 24 '23 at 06:35

0 Answers0