Why is this 'feelings' showing up as an object instead of what I enter in the textfield?a

Viewed 29
  • when I console.log(feelings) it prints the inputted text value in the form.

  • However when I try to add 'feelings' to the object and update the ui with it I get [object Object]

  • when you use feelings.value down in the async code it works just fine. isn't feelings.value === .value.value??

<div class ="holder zip">
    <label for="zip">Enter Zipcode here</label>
    <input type="text" id="zip" placeholder="enter zip code here">
  </div>
  <div class ="holder feel">
    <label for="feelings">How are you feeling today?</label>
    <textarea class= "myInput" id="feelings" placeholder="Enter your feelings here" rows="9" cols="50"></textarea>
    <button id="generate" type = "submit"> Generate </button>
  </div>

    function generate (e) {
      const zipcode = document.querySelector('#zip').value;
      const feelings = document.querySelector('#feelings').value;
      console.log(zipcode)
      console.log(feelings)
    
      getWeather(baseURL+zipcode+apiKey)
      .then(function(data){
        postData(data)
      })
      .then(updateUI)
    }
    /* Function to GET Web API Data*/
    const getWeather = async (url = '') => {
      const response = await fetch(url);
    
      try {
        const weatherData = await response.json();
        weatherData['date'] = newDate; 
        weatherData['feelings'] = feelings; //where it displays as an {} unless use feelings.value
        console.log(weatherData);
        return weatherData;
    
      } catch(error){
        console.log('error', error);
      }
    }



1 Answers

feelings is not just any random object, it's your textarea element. This weird behavior is a bad feature of chrome and some other browsers; they assign DOM elements with ids to global variables named after the ids, read more about it on this other SO question: Do DOM tree elements with ids become global variables?

Since you're not passing feelings from generate to getWeather, the feelings used is the global variable created by the browser which is the DOM element, an object. In other words, the global variable feelings is not shadowed, so it is used.

To fix this, simply pass feelings as an argument from generate to getWeather like so:

function generate (e) {
  //...
  getWeather(baseURL + zipcode + apiKey, feelings)
  // ...
}

const getWeather = async (url, feelings) => {
  // here the parameter 'feelings' is used rather than the global variable 'feelings'.
}
Related