如何从脚本提交表单

时间:2015-10-29 09:50:59

标签: javascript forms

我有一个简单的表格:

tableView.cellLayoutMarginsFollowReadableWidth = false

<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()

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

2 个答案:

答案 0 :(得分:2)

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

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

答案 1 :(得分:1)

您需要定义表单的名称。定义此表单后,可以使用javascript提交。

要查看示例,您可以按照此示例 -

<form name="myform" action="handle-data.php">
Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
  document.myform.submit();
}
</script>