Tuesday, June 26, 2007

Javascript Copy Selected Text Box Select All Highlight Text

The below link is
Javascript Copy Selected Text Box Select All Highlight Text

www.wallpaperama.com

But this will not work in firefox
because document.selection.createRange() is undefined
You need something like
Code:
if (window.getSelection)
{
txt = window.getSelection();
foundIn = 'window.getSelection()';
}
else if (document.getSelection)
{
txt = document.getSelection();
foundIn = 'document.getSelection()';
}
else if (document.selection)
{
txt = document.selection.createRange().text;
foundIn = 'document.selection.createRange()';
}
else return;
Too bad later i found that window.getSelection will not work in textarea.. and yet this is bug for firefox according
http://www.squarefree.com

Code:
function copyit(theField) {

var selectedText = document.selection;

var txt;
var foundIn;

if (window.getSelection)
{
txt=getSelectionInfo(theField);
//alert('ori='+theField.value.length);
//alert('new='+txt.length);
if(txt.length==theField.value.length )
theField.value='';
}
else if (document.getSelection)
{
alert('2='+document.getSelection);
txt = document.getSelection();
foundIn = 'document.getSelection()';
theField.focus();
theField.value = txt;
}
else if (document.selection)
{
alert('3='+document.selection);
if (document.selection.type == 'Text') {

txt = document.selection.createRange().text;
alert('ori='+theField.value.length);
alert('3='+txt.length);
if(theField.value.length==txt.length)
alert('clearAll!!');
foundIn = 'document.selection.createRange()';
theField.focus();
theField.value = txt;
}
}
else return;

;

}
function getSelectionInfo(theField)
{
var rv = "";
var i,x;

x = theField;

rv += x.value.substr(x.selectionStart, x.selectionEnd - x.selectionStart);

if(x.selectionStart==0 && x.selectionEnd==x.value.length)
return rv;
}

No comments: