簡體   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