Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cannot select text with Firfox!

Status
Not open for further replies.

Volatire666

Programmer
Nov 30, 2008
2
Here is the scenario: I have a textarea with text in it and I want to select/highlight predefined text within the textarea with a function. This code using ranges works with IE -

selectText = function(node, text)
{
var range = document.body.createTextRange();
range.moveToElementText(node);
range.findText(text);
range.select();
}

Firefox handles ranges completely differently and is not very well documented. I have got as far as creating a range which includes all the text in the textarea -

var range = document.createRange();
range.setStart(node, 0);
range.setEnd(node, 1);

I'm not sure where to go from here. Any further ideas on how to create a selection of text within a textarea?
 
I've finally figured it out for anyone else with similar problems:

selectText = function(node, text)
{
if (window.getSelection)
{
node.selectionStart = node.value.lastIndexOf(text);
node.selectionEnd = node.value.lastIndexOf(text) + text.length;
node.focus();
}
else if (document.selection && document.body.createTextRange)
{
var range = document.body.createTextRange();
range.moveToElementText(node);
range.findText(text);
range.select();
}
}

This should work with the latest IE and Firefox. I've not tested it on anything else.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top