2016-01-24 94 views
0

我試圖自動填充文本框1至3與主文本框的內容,以便無論輸入文本框「標題」也會出現在文本框中 Input1,Input2和Input3。這是我的,但我得到一個錯誤。用主文本框內容自動填充文本框

<html> 
<head> 
<script type="text/javascript"> 
    function CopyData(val){ 
    var a = document.getElementById(val.id).value 
    document.getElementById("CopyText").value=Title 
    } 

    </script> 
</head> 
<body> 

Title:<input type="text" name ="Title" id="Text" onkeyup="CopyData(this)"/><br /> <br /> 
Input 1:<input type="text" name ="Input1" id="CopyText"/><br /> 
Input 2:<input type="text" name ="Input2" id="CopyText"/><br /> 
Input 3:<input type="text" name ="Input3" id="CopyText"/><br />                

</body> 
</html> 
+1

請告訴我們你得到了哪個錯誤。並且:爲什麼你對多個元素使用相同的ID? –

+0

元素'ID'值必須是唯一的。 –

回答

1

嘗試了這一點:

<html> 
<head> 
<script type="text/javascript"> 
    function CopyData(val){ 
    var a = document.getElementById(val.id).value 
    var inputs = document.querySelectorAll(".input"); 
    for(var i=0;i < inputs.length;i++) 
    { 
     inputs[i].value = a; 
    } 

    } 

    </script> 
</head> 
<body> 

Title:<input type="text" name ="Title" id="Text" onkeyup="CopyData(this)"/><br /> <br /> 
Input 1:<input type="text" class="input" name ="Input1" /><br /> 
Input 2:<input type="text" class="input" name ="Input2" /><br /> 
Input 3:<input type="text" class="input" name ="Input3" /><br />                

</body> 
</html> 

備註:

  1. 沒有使用相同的id多個元素。嘗試類而不是
  2. 您使用未定義的'標題',使用「a」,這是你存儲輸入值的地方
  3. 一次用簡單的js獲取許多元素,好方法是使用「querySelectorAll」與適當的選擇器。

祝你好運。

0

我想你不能把同一個id標籤分配給多個TextBox,所以你必須得到一個更加「硬編碼」的javascript函數。此外,我會用Title.value不僅標題

function CopyData(){ 
document.getElementById("CopyText1").value=Title.value; 
document.getElementById("CopyText2").value=Title.value; 
document.getElementById("CopyText3").value=Title.value; 
}