繁体   English   中英

Javascript在文本框之间传递数据

[英]Javascript passing data between text boxes

我正在使用javascript将数据从一个文本框转到另一个文本框。 我是Java的新手,正在获取文档未定义或空错误。

<!DOCTYPE html>
 <html>
  <head>
    <script>
      function doit() {
        window.document.form1.txtbox1.value= window.document.form2.txtbox2.value;
      }
   </script>
  </head>
 <body>

   <form name="form1">
     Enter your name:
     <input type="text" name="txtbox1" value="">
     <input type="button" name="btn1" value="Click" onclick="doit()">
   </form>

   <br><br><br>
   <form name="form2">
     Results: 
     <input type="text" name="txtbox2" value="">
   </form>

 </body>
</html>

似乎您尝试将元素作为DOM的属性进行访问。

相反,您应该使用document.getElementsByName方法。

修改功能:

function doit(){
// The [0] is for accessing the first item.
// If you are unfamiliar with arrays, visit
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
  document.getElementsByName("txtbox1")[0].value = document.getElementsByName("txtbox2")[0].value;
}

您需要切换(交换)它们: window.document.form1.txtbox1.value= window.document.form2.txtbox2.value;

单击按钮时-将第二个输入的值设置为第一个输入,可能称为“结果”的第二个输入为空。

尝试:

      function doit() {
        window.document.form2.txtbox2.value = window.document.form1.txtbox1.value;
      } 

不应有任何错误,它只是按照您可能期望的方向传递数据。

给两个输入元素一个唯一的ID。

<input type="text" id="txtbox1" value="">
<input type="text" id="txtbox2" value="">

和功能doit()

document.getElementById("txtbox2").value = document.getElementById("txtbox1").value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM