Function doesn't return value after onclick using JavaScript

Viewed 42

This is my code:

var global;
document.getElementById("Updatebtn").addEventListener("click", myFunction);

function myFunction() {
 var x = document.getElementById("start");
 var defaultVal = x.defaultValue;
 var currentVal = x.value;
 global = currentVal;
 return(global)
 }

console.log(global)

Html:

<input type="date" id="start" name="trip-start" value="2022-09-09" 
min="2022-09-09" max="2022-12-31"></input> 
<button class="ul-label" type="button" id = "Updatebtn"> Update 
</button><br><br>

I tried without return too but no hope, all I need is to update and use the variable outside the function everytime the button is clicked

I tried using Async based on one of the posts but I am confused on how Async works, as it doesn't react to the button input:

document.getElementById("Updatebtn").addEventListener("click", delay);


async function delay() {
  var x = document.getElementById("start");
  // `delay` returns a promise
  return new Promise(function(resolve, reject) {

  // Only `delay` is able to resolve or reject the promise
  setTimeout(function() {
  var defaultVal = x.defaultValue;
  var currentVal = x.value;
  resolve(currentVal); // After 3 seconds, resolve the promise with 
  value 42
  }, 3000);
  });
  }

  delay()
   .then(function(v) { // `delay` returns a promise

   console.log(v); // Log the value once it is resolved
  })
   .catch(function(v) {
    // Or do something else if it is rejected
    // (it would not happen in this example, since `reject` is not 
    called).
    });
0 Answers
Related