0

I googled, and looked at stackoverflow and tried out the examples and i'm still having difficulties.

GOAL: Create a form box where a user can enter a city name so i can capture it in a variable and use it to look up the city lattitue and longitute from goodle geocode api.

Here is the HTML:

<div>
  <form id="nameForm">
    <input id="cityForm" type="text" >
    <button id="subButton" type="button">Submit</button>
  </form>
</div>

and here is my code i tried:

var theTerm = document.getElementById('cityForm').value; console.log(theTerm);

console output gives me nothing.

I stripped the code down and removed the weather api stuff from it but basically i'm concerned about how i can capture a city name that was entered and 'submit' by a user. Here is the jsfiddle: https://jsfiddle.net/zt28sbo3/1/

1
  • shouldn't you wait for user to enter something? Think it through a bit... page loads....you try to get a value immediately, before user can even see the form. What's the button for then? Commented Feb 11, 2017 at 21:56

1 Answer 1

1

You need to wait for an event (when the user has typed something). Something like so should work:

var element = document.getElementById('foo');
element.addEventListener('blur', function () {
  var value = this.value;
  // API request here
});
<input id="foo" />

You could also listen to the parent forms submit event:

var form = document.getElementById('nameForm');
form.addEventListener('submit', function (e) {
  e.preventDefault(); // Prevent normal form submission
  var value = document.getElementById('foo').value;
  console.log(value);
  // API request here
});
<form id="nameForm">
  <input id="foo" />
  <button type="submit">Submit</button>
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

not so sure that is the most appropriate event for allowing user to enter a city name in order to make an api request
Wow, nice answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.