我们可以将表单元素值传递给同一网页中的函数吗?

时间:2012-12-27 15:38:55

标签: javascript html forms

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

 }
 </script>
 </html>

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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);
 }
}