iBim's da Michi
iBim's da Michi

Reputation: 23

How to get text from input form?

Input form: I can type random text and get the output in the console, like so: "getWeather.html?city=London:76"

This is the code:

HTML:

<form>
    <input type="text" name="city" placeholder="Enter City here..">
    <input type="submit" value="Submit">
</form>

javaScript:

var input = $('input')[0].form.city.value;
console.log(input);

However, I would like to get the input directly into a variable. In this case 'London'.

Upvotes: 0

Views: 1440

Answers (1)

Nicolas
Nicolas

Reputation: 8695

From what i understand, the way you are getting the city value is wrong. Here I'm using a JQuery selector with an attribute value lookup. The selector basicly says: Look for every input with the attribute name equals to city.
Then i'm using the val() function to get the value. I've added a ev paremeters which is the Javacript event and i have stopped it using ev.preventDefault();. This prevent the page from reloading.
To conclude, I've simply console.log the value.

$('form').on('submit', function(ev) {
  ev.preventDefault();
  var value = $('input[name=city]').val();
  console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="text" name="city" placeholder="Enter City here..">
    <input type="submit" value="Submit">
</form>

Upvotes: 2

Related Questions