Splitting is simple:
function test(pastedText) {
var parts = pastedText.split(Chr(9));
document.getElementById("text1").value = parts[0];
document.getElementById("text2").value =
(parts[1] === undefined ? "" : parts[1]);
}
The tricky part, actually is the pasting, check the full code below.
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>
I also suggest you rename the test()
function into something more meaningful to you.