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

I am struggling to increase the width of my input bar and center-align it

Below is the CSS class I've created to ensure that all elements remain centered on the user's screen. container: { display: "flex", position: "absolute", top: 0, left: 0, height: "100%&qu ...

Explore Python and Selenium for implementing pagination with JavaScript functionality

Having recently started using Selenium with Python 2.7, I am looking to click on certain JavaScript elements used for pagination on a website. To provide context, here is the link to the page: . Any guidance or example code would be greatly appreciated. ...

Connect CSS Transition to a click action

Below is the code snippet. When you click on the div, it creates a folding effect to the left. You can view it here. I want to link this effect to the arrows I use for sliding back and forth. For example: The left arrow should move the slide to the l ...

Exploring Node.js Express: Understanding the Difference Between Modules and Middleware

I am working on an express rest api and need to create a PDF document with a link to download it. I have successfully generated the PDF, but now I want to create a route specifically for returning the PDF link. In addition, I also need other routes that ...

Problematic Angular 6 Lazy Loading Situation

Below is the code snippet I am using for lazy loading: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'manager', lo ...

Build a custom form for the purpose of exporting an HTML file

I am in search of a way to provide my users with various "feature" choices that will assist them in creating an HTML file for an email. I already have the code ready for each feature, but I want users to be able to select a feature (such as Hero Image Head ...

Retrieve an XML document using AJAX and then convert it to JSON format without needing a server

Seeking assistance with a code snippet I'm currently working on. Unfortunately, my knowledge of AJAX and jQuery is limited. Here's the issue: I am trying to retrieve XML data from an external XML file (text.xml) and convert it into a JSON object ...

Adjust the color of text, image, and background when the cursor hovers over

Is it possible to change the color of an image on hover by applying a filter like brightness(10)? I tried this, but it whitens all the button, so now I'm not sure how to change the icon color. https://i.sstatic.net/nJL1i.gif One way to do it is: ...

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

Chakra UI Not Displaying Proper Responsiveness on the User Interface

I recently integrated Chakra UI for styling a project on Next.js, and while most components are functioning properly, I am facing challenges with implementing responsive layouts. The styles do not seem to adapt when the screen size is reduced. Here's ...

Why can I only click on the text of my button?

Looking for a quick fix here! I've been trying to make the entire button clickable, but so far, only the text is hyperlinked. Any suggestions on how to enclose the whole button with the link? As you can see, I'm working on making it mobile-friend ...

The handlebar does not undergo any modifications once the authentication process is completed

This file is named header.hbs <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{{ title }}</title> ...

What is the main file that vue-cli-service utilizes for entry?

Interested in a project utilizing vue, webpack, babel, npm? You can launch it with npm run server. While exploring how this command functions, I came across vue-cli-service serve in the package.json file. But how exactly does vue-cli-service initialize ...

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

Icons will be displayed when hovered over

Is it possible to display icons on hover in a div and hide them otherwise using just CSS? Or do I need to use javascript for this function? Thanks in advance! Example: HTML: <div id="text_entry"> <p>Some text here</p> <span ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

Protractor's count() function fails to execute properly when called outside of a promise loop

var alerts = element.all(by.xpath("//div[@class='notification-content']")); alerts.count().then(function (val) { console.log(val); }); let compareValue = val; Is there a way to access the 'value' outside of the promise l ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

Issue with Swiper JS: The buttons on pages three and beyond are unresponsive

I'm having trouble with the functionality of the "Back" button on pages 2 and 3 of my website. Can anyone help me figure out why it's not working? My goal is to create a website that resembles a game menu, similar to Deus Ex The Fall. I'm u ...