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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prevent Select

Status
Not open for further replies.

alsaffar

Programmer
Oct 25, 2001
165
KW
Hi everybody,

I'm using a havascript code to prevent selecting text or right click on my web page, but the problem is I want to enable right click and text selecting inside a specific textarea and text input, how can I acheive that?

The code Im using:

<script type='text/javascript'>
function clickIE()
{
if (document.all)
return false;
}

function clickNS(e)
{
if (document.layers||(document.getElementById&&!document.all))
if (e.which==2||e.which==3)
return false;
}

if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS;
}
else
{
document.onmouseup=clickNS;
document.oncontextmenu=clickIE;
}
document.oncontextmenu=new Function('return false');

document.onselectstart=new Function('return false');
function ds(e){return false;}
function ra(){return true;}document.onmousedown=ds;document.onclick=ra;
</script>
 
Try out the UNSELECTABLE property in your fields.

Or one I have never tried goes like this:
<body onselectstart="return false">
This would be global on the page though so each time they try to select text it would return false and cancel the operation.
 
Thanx theniteowl for your help,

Please take a look on the following code, with this code you can't select text in the whole page:

<html>
<body onselectstart="return false">
sample text
<TEXTAREA>sample text 2</TEXTAREA>
sample text 3
</html>

How to enable selecting text ONLY inside the textarea?
 
I have never used onselectstart but saw that bit of code on another site.

Tested it myself here and it did not seem to do anything when applied directly to an element so I looked it up.
You can read about it at:

So I tried using it with a legitimate function call and it works. It let's you select the box you want so that you can type in if needed but if you try highlighting data in that field it triggers the javascript function. From that function you could pop up a message or just return control back to the script again effectively causing the selection to be canceled.

<html>
<head>
<script type="text/javascript">
function mytest()
{
alert("Dont do that");
}

</script>
</head>

<body>
<div onselectstart="mytest();">
<input type="text" name="test1" size="20"><br>
<input type="text" name="test2" size="20"><br>
</div>

</body>
</html>

Now, you can probably apply this to a DIV or SPAN tag so that you can have the one command to apply to all elements within that tag and make your code a bit cleaner.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top