简体   繁体   中英

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'.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM