views:

386

answers:

3

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.

A: 

If you can live with using JQuery, then cloning can be done this way:

$("#input1").keyup(function() { 
  $("#input2").val( $("#input1").val() );
}
Zed
A: 

You can do the first part you ask about (like my answer here), but not the 2nd part - it's just not possible to have more than one active selected range at a time.

Peter Bailey
+1  A: 

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>
Ionuț G. Stan
I'm not even sure if those browsers support selection of multiple parts on the page at the same time.
Litso
Works nicely in Firefox. I had no idea multiple selections were possible.
artlung
I should clarify: tested in FF 3.5.2 and works great.
artlung
I guess @timhessel is almost right. Opera, IE and Chrome don't support multiple selection when I manually select using CTRL. Nevertheless the above solution works in Opera, is just that the second selection is of a different color. I wonder what's the support of multiple selection using Range objects...
Ionuț G. Stan
Unfortunately, I don't seem to come up with a cross-browser solution.
Ionuț G. Stan
Very nice! Unfortunately, I need IE to work too. Even more than FF.
ntownsend