Home > Software engineering >  How do you take a variable from a function that takes an input from an html form and use it in anoth
How do you take a variable from a function that takes an input from an html form and use it in anoth

Time:10-18

here i am taking a input from a drop down form on a html page. And i am putting it in to a var called AM.

 var e = document.getElementById("UserTimeAM");
    function onChangeAM() {
      var AM = e.value;
      var text = e.options[e.selectedIndex].text;
      console.log(AM, text);
    }
    e.onchangeAM = onChangeAM;
    onChangeAM();

From there a fetch is called to an api and i am using the AM variable in it. But the issue is that when the site is being served it comes back with an error saying AM is not defined.

lowHigh.forEach(d =>{
    let wDate = new Date(d.time).getUTCDate();
    let AM_Hour = AM;
    let PM_Hour = PM;
    AM_Hour = ("0"   AM_Hour);

    if(wDate == i 1)
        {
            if(tidedata1.innerHTML == "")
            {
                
                tidedata1.innerHTML = `${AM_Hour}: - ${d.value}m`
                tidedata1Full.innerHTML = `${AM_Hour}:am - ${d.value}m`
            }
            else
            {
                tidedata2.innerHTML = `${PM_Hour}: - ${d.value}m`
                tidedata2Full.innerHTML = `${PM_Hour}:pm - ${d.value}m`
            }
        }
    })

I thought using var would mean it was a global so the variable could be passed in to different functions.

CodePudding user response:

You just need to initialize the AM variable in the scope outside of your two functions to make it possible to use it in both

var AM;
var e = document.getElementById("UserTimeAM");
    function onChangeAM() {
      AM = e.value;
      var text = e.options[e.selectedIndex].text;
      console.log(AM, text);
    }
    e.onchangeAM = onChangeAM;
    onChangeAM();

lowHigh.forEach(d =>{
    let wDate = new Date(d.time).getUTCDate();
    let AM_Hour = AM;
    let PM_Hour = PM;
    AM_Hour = ("0"   AM_Hour);

    if(wDate == i 1)
        {
            if(tidedata1.innerHTML == "")
            {
                
                tidedata1.innerHTML = `${AM_Hour}: - ${d.value}m`
                tidedata1Full.innerHTML = `${AM_Hour}:am - ${d.value}m`
            }
            else
            {
                tidedata2.innerHTML = `${PM_Hour}: - ${d.value}m`
                tidedata2Full.innerHTML = `${PM_Hour}:pm - ${d.value}m`
            }
        }
    })

CodePudding user response:

The problem


In order to fully understand the differences between each of the identifiers (let, var, const) we first need to understand the concept of scope.

What is Scope? Scope determines the accessibility or visibility of variables to JavaScript. There are three types of scope in JavaScript:

  1. Global scope

  2. Function (local) scope

  3. Block scope (new with ES6)


- Global Scope Variables declared outside a function are in the global scope. Global variables can be accessed and changed in any other scope.

- Local Scope Variables defined within a function are in local scope and are not accessible in other functions.

Each function, when invoked, creates a new scope, therefore variables with the same name can be used in different functions.

Reference: JavaScript: Var, Let, or Const? Which One Should you Use?

Example


var first = 123;

if(true) {
  var second = 456;
}

function abc(){
  var third = 789;
}

abc();

Note that first and second are inside global scope, and third is in function (local) scope, because its declared inside a function

Important note


Variables declared using the var keyword are either globally or functionally scoped, they do not support block-level scope. This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.

Example:

function DoSomething(){
  if(true){ //Some condition [only example]
     var example = 123;
  }

  console.log({example})
}
DoSomething()

If it had been declared as a let, it would not be visible, and would belong to the ({}) block of the if, example:

function DoSomething(){
  if(true){ //Some condition [only example]
     let example = 123;
  }

  console.log({example})
}
DoSomething()

In this example above, i'm using let, with will generate an error, that is a good thing to alert the programmer.

How to solve


Just as @HaimAbeles said, you just need to initialize the AM variable in the scope outside of your two functions to make it possible to use it in both

Example:

var AM;
var e = document.getElementById("UserTimeAM");
    function onChangeAM() {
      AM = e.value;
      var text = e.options[e.selectedIndex].text;
      console.log(AM, text);
    }
    e.onchangeAM = onChangeAM;
    onChangeAM();
...
  • Related