Disallowing selection on input text field

I am seeking to disable selection on an input field while still allowing for focusing, with the following criteria:

  • Preventing selection via mouse
  • Preventing selection via keyboard (including Ctrl+A, shift+arrows)
  • Permitting focus on the field using both keyboard and mouse

My attempts so far have included:

CSS

I have tried applying the following class:

.unselectable {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Outcome: Selection is still possible.

I have also experimented with the below code without success:

$("#my_field").attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', 
           '-webkit-user-select':'none',
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

Javascript

I attempted the following:

$( "#my_field" ).select(function(e) {
        console.log("Select called");
        e.preventDefault();
});

Outcome: The message was printed in the console, but selection still occurred.

Thank you for any assistance provided.

Answer №1

To achieve this, simply set the selectionStart of the element equal to its selectionEnd when the select event is triggered:

var input = document.getElementById('my_input');

input.addEventListener('select', function() {
  this.selectionStart = this.selectionEnd;
}, false);
<input id="my_input" type="text" value="Click here to select text" />

Answer №2

To overlay the <input> with a layer in absolute position, you can use div.wrapper::after or another wrapper tag. Then apply user-select: none to the wrapper tag (<div>, <label>, etc) and avoid using user-select: none directly on the <input>.

If your wrapper tag is <label>, it's recommended to also add the readonly attribute to the <input> and convert the <label> to block display (or inline-block / flex / inline-flex).

input { outline: none; margin: 10px 0; width: 200px; }

.wrapper {
  position: relative;
  user-select: none;
}

.wrapper::after {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

label.wrapper { display: block; }
<div class="wrapper">
  <input type="text" value="Any text in the div wrapper"/>
</div>

<label class="wrapper">
  <input type="text" value="Any text in the label wrapper" readonly />
</label>

Answer №3

If you want to prevent the mousedown event from allowing text selection within an input element, you can use the following code:

<input type="text" id="unselectable" value="You can not select this text!"/>
<script>
document.getElementById("unselectable").addEventListener("mousedown", function(event){
  event.preventDefault();
});
</script>

Answer №4

Solution using only CSS:

This method does not visually show the selected text in an input field while still allowing it to be selected.
In some cases, this approach may suffice if the focus is on the visual appearance of the selection rather than its functionality.

input{ color:transparent }
input::selection{ color:transparent }
<input value='invisible selection'>

Another option is to use font-size:0 along with defining the width and height for the input element.

Alternative Solution using JavaScript:

Force the input to lose focus when it gains focus by triggering the blur method:

<input value='unselectable selection' onfocus='this.blur()'>

Answer №5

Here is the answer for adding a pointer icon to your cursor.

.selection-box {
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  cursor: pointer;
}

.selection-box::after {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="selection-box">
  <input type="text" value="click here"/>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...

Change the font style of individual characters within a string using CSS or JavaScript, instead of applying it to the entire

Is it feasible to assign a specific font to a particular character? I would like: #test_id{ font-family: "digitalfont"; font-family-of-, : "HelveticaNeue-Light"; } In order to set a font for a comma and a separate font for the rest, do I need to ...

Is it possible to alter CSS attributes dynamically without setting a limit on the number of changes that can be made?

In my current project, I am looking to add a feature that allows users to choose the color scheme of the software. While the choices are currently limited, I plan to implement a color picker in the future to expand the options available. So far, I have ex ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

What are some ways to prevent having to constantly check for the existence of an object within another object when working

<template> <img :src="user.avatar_thumbnail"> <a :href="user.profile.link"/> </template> <script> export default { data: function () { user: {} }, ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

Issues with the functionality of the sliding menu in Angular are being encountered when trying to use $

Challenge I am facing an issue with a slider menu feature that I integrated into a mobile application for navigation purposes. The menu is functioning properly - it displays, allows flicking of the initial links, and can be closed by pushing the backdrop. ...

Creating a responsive carousel that is not yet designed

As a beginner, I'm facing what seems like a simple problem that I just can't solve. Here is the HTML code I've written: <div class="discs container"> <ul> <li><div class="arrowleft"><a href="#" >< ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Ensure the placeholder remains front and center, growing in size as it moves vertically

.inpsearch{ border:2px solid #bbb; border-radius:14px; height:29px; padding:0 9px; } .inpsearch::-webkit-input-placeholder { color: #ccc; font-family:arial; font-size:20px; } <input type='search' class='inpsea ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

Upon attempting to start the server, the module 'express-stormpath' could not be located

Upon trying to execute node server.js (in a regular terminal without superuser or root permissions), the following error is thrown: alphaunlimitedg@AUNs-PC:~/my-webapp$ node server.js module.js:442 throw err; ^ Error: Cannot find module 'expr ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

The useRef() hook call in NextJs is deemed invalid

I have been attempting to implement the useRef() hook within a function component in my NextJs project, but I keep encountering the error below. Despite reviewing the React Hook guidelines, I am unable to determine why this error persists and the functio ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

What is the best method for incorporating a YouTube embedded video into an image carousel using HTML and CSS?

I'm encountering an issue with my product carousel that includes an image and a video. The image displays correctly, but when I attempt to click on the video to have it appear in the main carousel view, it doesn't function as expected. Here is a ...

Developing an export feature for a mean application

Attempting to develop a basic module for organizing accounts on a website seemed like a straightforward task. I thought it would be as simple as creating a file with some functions, wrapping it in module.exports, and everything would work smoothly. However ...

Clicking activates Semantic UI's dropdown function with the onClick method

I am experiencing an issue with the dropdown functionality on my website. Everything works fine until I add onClick() to the Semantic UI component. It seems like there are some built-in functions for handling onClick() within Semantic UI, so when I impleme ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...