Javascript: Adding selected text to an array
Posted
by joeybaker
on Stack Overflow
See other posts from Stack Overflow
or by joeybaker
Published on 2010-05-23T20:10:17Z
Indexed on
2010/05/23
20:20 UTC
Read the original article
Hit count: 332
JavaScript
|arrays
My goal: each time a user selects text, and clicks a button, that text gets added to an array. The problem: each time the button is pressed, the all objects of the array get overridden with the currently selected text.
I'd really appreciate help changing the behavior so that the selected text doesn't override all previous array items.
<script type="text/javascript">
var selects = new Array();
selects.push("1");
function getSelText()
{
var i = 0;
while (i<1) {
var txt = [null];
var x = 0;
if (window.getSelection)
{
txt[x] = window.getSelection();
}
else if (document.getSelection)
{
txt[x] = document.getSelection();
}
else if (document.selection)
{
txt[x] = document.selection.createRange().text;
}
else return;
selects.push(txt);
x++;
i++;
};
document.menu.selectedtext.value = selects;
}
</script>
<form class="menu" name="menu">
<input type="button" value="highlight" class="highlightButton" onmousedown="getSelText()"/>
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
© Stack Overflow or respective owner