0
 <html>
 <body>
 <form action="">
   ......any form elements......
 </form>
 </body>
 <script>
 function fn() {

 }
 </script>
 </html>

有没有办法(或任何其他替代方式)将表单值传递给同一网页中的函数(在脚本标签内),而不是 action 属性中的 URL?

4

2 回答 2

1

这是我多年来的做法。它适用于所有浏览器 - 对于真正旧的浏览器,如果您将 name="form1" 添加到表单标签,您甚至可以将 document.getElementById("form1") 更改为 document.form1。

注意:在 jQuery 之前,很多地方都推荐使用eventListeners,例如

document.getElementById("form1").addEventListener("submit",
  function(e) {
    e.preventDefault(); 
    ... some code 
  }); 

但我个人更喜欢 jQuery 或更简单的 onsubmit ......

<html>
<head>
<script>
window.onload=function() {
  document.getElementById("form1").onsubmit=function() {
    var val1 = this.field1.value;
    if (val1=="") {
      alert('Field1 cannot be empty');
      this.field1.focus();
      return false;
    }
    // return true to submit, return false to stay on the page.
    return true; 
  }
}
</script>
</head>
<body>
<form id="form1" action="">
  <input type="text" name="field1" value="" />
  .
  .
  .
</form>
</body>
</html>

如果它必须是内联的,那么我强烈推荐

<head>
<script>
function validate(theForm) {
  var val1 = theForm.field1.value;
  .
  .
    return false;// cancel
  .
  .
  return true; // allow submit
}
</script>
</head>

<form onsubmit="return validate(this)">

更新

to just change some span or div on the page do this:

<html>
<head>
<script>
window.onload=function() {
  document.getElementById("form1").onsubmit=function() {
    var val1 = this.field1.value;
    document.getElementById("div1").innerHTML="This is the value "+val1;
    return false; // do not submit/refresh the page
  }
}
</script>
</head>
<body>
<form id="form1" action="">
  <input type="text" name="field1" value="" />
  <input type="submit" />
</form>
<div id="div1"></div>
</body>
</html>
于 2012-12-27T16:05:33.697 回答
0

html

<form  id="frm">    
<input type="button" onclick="fn()" value="Submit to function"/>
</form>

javascript

function fn(){
var frm = document.getElementById("frm");
var elements = frm.elements;
var len = elements.length;
// do something with elements
 for(var i =0; i < len; i++){
  console.log("%s = %s", elements[i].name, elements[i].value);
 }
}
于 2012-12-27T15:44:24.443 回答