Javascript Disable Input Text Selection

Updated on 23 Mar 2012,
Published on 04 Jul 2008

Javascript also provides the functionality to disable the text selection of input fields as well as HTML document text using mouse selection event. You can use Javascript return false to prevent the user from text selection. return false disables the selection events such as onselect, onselectstart and onmousedown. These events are commonly used to select the text displayed on the HTML document or input fields on the HTML web forms. HTML input fields support the onselect and onmousedown event where HTML document body element supports the onselectstart and onmousedown event.

JavaScript DOM Examples:

You can see the live samples and examples of JavaScript DOM from the following links:

Example of Javascript Code to Disable Input Text selection

<body onmousedown="javascript:return false;" 
        onselectstart="javascript:return false;">
<input onselect="return false" 
        onmousedown="return false" 
        type="text" 
        value="disabled text" />

First example shows the use of return false for onmousedown and onselectstart event of body tag of HTML web page. These events will disable the user to select the open text or content present on the web page.

Second example shows the use of return false for onselect and onmousedown event of input type text field that will disable the user from text selection of input field. Combination of javascript and these events make the input field read-only for the users.

Output:

You can see the output of above discussed codes from the following link:

Disable Input Text Selection

Continue to next tutorial: Javascript Create New Div HTML Element Dynamically to learn how to add HTML Div element on HTML page body dynamically.

0 Responses to "Javascript Disable Input Text Selection"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers