Search code examples
javascripthtmldomselectiontextrange

How can I mirror text selection?


Say you have two inputs:

<input id="input1" type="text"/> and <input id="input2" type="text"/>

such that through some JavaScript magic, anything you type in input1 will also be put in input2. In this sense input2 "mirrors" input1.

Is there a way that I can also "mirror" text selection. So if I select some text in input1, how can I have the exact same text in input2 also be selected?

I've been looking at Microsoft's TextRange object and the Selection object used by Mozilla et al, but the whole mess seems pretty cumbersome. Has anyone had any success doing something like this before?

CLARIFICATION: Thanks for the responses so far. To be clear: I'm not asking how to mirror the text. I've already solved that one. The question is only about selecting the text in input1 and having the corresponding text in input2 also be selected.


Solution

  • It's very easy in Firefox and Opera as far as I see. Google Chrome and IE not so much. Here's the code that works in FF:

    <!DOCTYPE html>
    
    <html>
    <head>
    <meta charset="UTF-8">
    </head>
    <body>
    
    <input type="text" size="40" id="sel-1" value="Some long text">
    <input type="text" size="40" id="sel-2" value="Some long text">
    
    <script type="text/javascript">
    var sel_1 = document.getElementById("sel-1");
    var sel_2 = document.getElementById("sel-2");
    
    document.onmousemove = function () {
        sel_2.selectionStart = sel_1.selectionStart;
        sel_2.selectionEnd   = sel_1.selectionEnd;
    }
    </script>
    </body>
    </html>