2013-08-03 150 views
2

我在html文件text1和text2中有2個輸入字段。然後我複製一個長字符串並將其粘貼到text1中。我希望字符串自動分割成text1和text2。所以在字符串中必須有一個分隔符,例如TAB(ASCII 9)。我一直在嘗試很多次,但沒有幸運。在我的實驗,有一個按鈕調用javascript函數如下:如何將字符串拆分爲多個html文本字段

<script> 
function Chr(AsciiNum) 
{ 
return String.fromCharCode(AsciiNum) 

} 

function test() 
{ 
    c = "ABC"+Chr(9)+"DEF"; 
    document.getElementById("text1").value=c; 
} 

</script> 

<input type="button" value="Paste it" onClick="test()"> 

我要的是text1中充滿了ABC和文本2充滿了「DEF」

感謝您的幫助.....

回答

0

你爲什麼不只是做這樣的:

c = "ABC "+Chr(9); 
document.getElementById("text1").value=c; 
document.getElementById("text2").value= "DEF"; 

這應該是內部test()

希望這有助於。

+0

在我的情況下,有一個Web應用程序根本無法訪問源代碼。因此,我嘗試製作自己的表單,其中包含與應用程序相似的輸入。然後oparator只需要複製到剪貼板(通過單擊)並粘貼到基於Web的應用程序中的第一個字段,其他字段自動提交。謝謝你很多 –

+0

你在哪裏製作這個表格?你把代碼放在哪裏? –

1

分割很簡單:

function test(pastedText) { 
    var parts = pastedText.split(Chr(9)); 

    document.getElementById("text1").value = parts[0]; 
    document.getElementById("text2").value = 
             (parts[1] === undefined ? "" : parts[1]); 
} 

棘手的部分,實際上是粘貼,檢查下面的全部代碼。

See a online DEMO for code here

Text1: <input type="text" id="text1"><br /> 
Text2: <input type="text" id="text2"><br /> 
<br /> 
<div>Sample string (copy the red text and paste it on Text1):</div> 
<div style="color:red">ABC DEF</div> 

<script> 
    function Chr(AsciiNum) { 
     return String.fromCharCode(AsciiNum) 
    } 

    function test(pastedText) { 
     var parts = pastedText.split(Chr(9)); 

     document.getElementById("text1").value = parts[0]; 
     document.getElementById("text2").value = (parts[1] === undefined ? 
                   "" : parts[1]); 
    } 

    /** HANDLING PASTE EVENT 
    * Credits to: http://stackoverflow.com/a/6035265/1850609 */ 
    function handlePaste(e) { 
     var pastedText = undefined; 
     if (window.clipboardData && window.clipboardData.getData) { // IE 
     pastedText = window.clipboardData.getData('Text'); 
     } else if (e.clipboardData && e.clipboardData.getData) { 
     pastedText = e.clipboardData.getData('text/plain'); 
     } 
     test(pastedText); // Process and handle text... 
     return false; // Prevent the default handler from running. 
    }; 
    document.getElementById("text1").onpaste = handlePaste; 
</script> 

我也建議你重命名test()功能到更多的東西對你有意義。

+0

感謝您的回答。但是如果沒有辦法訪問我們想要粘貼到它的應用程序的源代碼.. –

+0

我不明白:如果你無法訪問源代碼,你想做什麼?你想要改變/達成什麼? – acdcjunior

+0

感謝acdcjunior,上面的代碼完全像我想要的那樣運行,除了紅色文本不應該存在於同一個頁面中,我「我不是」修改了我應該粘貼到的頁面的代碼。所以我不可能添加任何代碼片段,請求TEXT1和TEXT2。 –

相關問題