javascript - 如何从脚本提交表单

标签 javascript forms

我有一个简单的表格:

<form id="form" method="post" action="email.php">      
  <input id="name" name="name" type="text" placeholder="Name" />   
  <input name="email" id="email" type="text" placeholder="Email" />
  <textarea name="text" id="msg" placeholder="Comment"></textarea>
  <input type="button" value="SUBMIT" id="submit" onclick="empty()"/>
</form>

和一个 empty() 函数,用于检查是否所有输入都存在:

function empty(){
    var x; var y; var z;
    x = document.getElementById("name").value;
    y = document.getElementById("email").value;
    z = document.getElementById("msg").value;
    if (x == "" || y == "" || z == "") {
        document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
        return false;
    }else{
         document.form.submit(); /*this doesn't work*/
    }
}

但我似乎无法提交表单...

最佳答案

问题出在按钮类型上。试试这个:

<script>
  function empty() {
    var x;
    var y;
    var z;
    x = document.getElementById("name").value;
    y = document.getElementById("email").value;
    z = document.getElementById("msg").value;
    if (x == "" || y == "" || z == "") {
      document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
      return false;  // the only reason this worked previously is that the input type was wrong so the form didn't submit
    } else {
      return true; // return true instead of trying to submit the form with js
    }
  }
</script>
<form id="form" method="post" action="email.php">
  <input id="name" name="name" type="text" placeholder="Name" />
  <input name="email" id="email" type="text" placeholder="Email" />
  <textarea name="text" id="msg" placeholder="Comment"></textarea>
  <input type="submit" value="SUBMIT" id="submit" onclick="return empty();" />
  <!-- change the button type to submit and return the value from the empty function (false will prevent the default action of the button - stop the form submitting, true will allow the form to submit) -->
</form>
<div id="errors"></div>

Noticed this doesn't work as a snippet so this is it working in a fiddle

关于javascript - 如何从脚本提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33410885/

相关文章:

javascript - 如何从 Wordpress 一页中删除#

css - 需要帮助对齐表单元素

javascript - 将文本框和提交按钮添加到 BIRT 报告中

java - JList高亮行问题

ruby-on-rails - 表单中的 Rails 选择标记不会填充编辑 View 中的值

javascript - 通过单击操作 CSS 变量

javascript - 谷歌地图嵌入API随时间出现的问题

javascript - ASP.NET MVC 根据 Ajax 请求更新 HTML 组件

javascript - AngularJS 获取元素进入 View

html - 如何使CSS搜索表单响应式