简体   繁体   中英

How to pass form element with onsubmit?

I am trying to pass the value submitted to my form into a function using onsubmit.

<form action="#" onsubmit="getWeather();return false">
    City: <input type="text" id="city">
    <input type="submit" />
</form>

So how would I pass the value of the city into the getWeather function? Thanks!

Name the field then pass in the value using this.city.value

<form action="#" onsubmit="getWeather(this.city.value);return false">
    City: <input type="text" name="city" id="city-field">
    <input type="submit" />
</form>

The function must be declared before using. You can do that inside a scrip tag before the declaration of the form:

<script>
    function getWeather(){
        var city = document.myform.city.value;     
        return false;
    }
</script>

And then add it in the html like here:

<form action="#" onsubmit="getWeather()" id="myform">
    City: <input type="text" id="city">
    <input type="submit" />
</form>

Best of Luck!

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