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>