how i can get (if)any text is selected in textbox and i want to get it in any variable of javascript.... specifically for Mozilla firefox...? Thanks in advance!
-
Note: the above description is not enough so let me give completely the definition.. My Extension of firefox is an Extension that double clicks any word from the webpage and finds its possible meaning from database... so user can even write anything in Textbox and double click the same for finding its meaning.. so please do suggest any way to complete selection from textbox's selected text....? in addition i am already using dblclick event handler so dont suggest that solution.... Thanxx in advancejyotin– jyotin2011年02月08日 11:28:48 +00:00Commented Feb 8, 2011 at 11:28
3 Answers 3
This should work:
alert(document.getElementById('TextBoxID').value);
And asigning that value to some variable:
var variablename = document.getElementById('TextBoxID').value
Edit: I just saw that you want to read only the selected text. This can be done this way:
if (TextBox.selectionStart != undefined)
{
var startPos = TextBox.selectionStart;
var endPos = TextBox.selectionEnd;
var selectedText = TextBox.value.substring(startPos, endPos)
}
alert("You selected: " + selectedText);
}
If you only need to know if a user has selected anything, you can do:
var hasSelected = (TextBox.selectionStart != undefined)
answered Feb 8, 2011 at 9:14
Chris
9,63717 gold badges61 silver badges76 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
T.J. Crowder
I think you missed the "...(if)any text is selected in textbox...".
value will give you all of the text in the textbox, regardless of whether it's selected.Lightness Races in Orbit
Even though he meant "whether".
answered Feb 8, 2011 at 9:17
Reto Aebersold
16.7k5 gold badges58 silver badges76 bronze badges
Comments
<script type="text/javascript">
function getSelText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
}
else if (document.selection) {
txt = document.selection.createRange().text;
} else {
return;
}
document.aform.selectedtext.value = txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()" />
answered Feb 8, 2011 at 9:18
Barrie Reader
10.7k11 gold badges77 silver badges141 bronze badges
Comments
lang-js