【问题标题】:How to pass form element with onsubmit?如何通过 onsubmit 传递表单元素?
【发布时间】:2018-04-08 22:33:09
【问题描述】:

我正在尝试使用 onsubmit 将提交给我的表单的值传递给一个函数。

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

那么如何将城市的值传递给 getWeather 函数?谢谢!

【问题讨论】:

  • document.getElementById('city').value 作为参数传递
  • 在(this.name.value)之间添加

标签: javascript forms variables onsubmit


【解决方案1】:

为字段命名,然后使用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>

【讨论】:

    【解决方案2】:

    函数必须在使用前声明。您可以在表单声明之前的脚本标记内执行此操作:

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

    然后将其添加到 html 中,如下所示:

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

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 2011-07-20
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 2021-03-13
      • 2023-03-22
      • 2021-05-24
      • 1970-01-01
      相关资源
      最近更新 更多