【问题标题】:Javascript passing data between text boxesJavascript 在文本框之间传递数据
【发布时间】:2018-02-24 14:55:12
【问题描述】:

我正在使用 javascript 将数据从一个文本框传输到另一个文本框。我是 Javascript 新手,我得到一个文档未定义或空错误。

<!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>

【问题讨论】:

  • 建议你先去学习JavaScript。我们选择像这样的标签document.getElementsByTagName("form"); 和类名document.getElementsByClassName("the-class"); 甚至是ID document.getElementById("the-id"); 或名称document.getElementsByName("form1");。还有很多其他的方法。欢迎迈克
  • 你是怎么得到undefinednull的?
  • 请解释期望的结果。

标签: javascript parameter-passing


【解决方案1】:

您似乎正在尝试将元素作为 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;
}

【讨论】:

    【解决方案2】:

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

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

    试试:

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

    应该没有任何错误,它只是按照您的预期将数据传递到另一个方向。

    【讨论】:

      【解决方案3】:

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

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

      在函数doit()中

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-19
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-23
        相关资源
        最近更新 更多