Deactivate a chosen item following selection

Is there a way to deactivate a selectable element after it has been clicked in the scenario below? Additionally, I would like to modify its CSS style.

$(function(){
  $("#selectable").selectable({
    stop: function() {
      var result = $( "#select-result" ).empty();
      $( ".ui-selected", this ).each(function() {
         var index = $( "#selectable li" ).index( this );
         result.append( " #" + ( index + 1 ) );
      });
    }
  });
});
    <!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Selectable - Serialize</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">

    <style>
      #feedback { font-size: 1.4em; }
      #selectable .ui-selecting { background: #FECA40; }
      #selectable .ui-selected { background: #F39814; color: white; }
      #selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
      #selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  </head>
  <body>
    <p id="feedback"><span id="select-result">none</span>.</p>
    <ol id="selectable">
      <li class="ui-widget-content">Item 1</li>
      <li class="ui-widget-content">Item 2</li>
    </ol> 
  </body>
</html>

I have attempted to achieve this by using the following code:

$("#selectable li").index(this).css('text-decoration', 'line-through');

However, it was unsuccessful in implementation.

The main objective is to prevent an element from being selected again once it has already been clicked by a user.

Answer №1

It may seem tricky at first, but it is definitely achievable.

To disable the pointer-events, simply add a CSS class (.selectable-disabled) to the selected items within your stop event handler.
Then utilize the filter option to restrict selection to only li:not(.selectable-disabled) elements.

If you wish to revert the items back to their original state, just remove the .selectable-disabled class (demonstrated with a button click in the demo below).

$( function() {
  $( "#selectable" ).selectable({
    filter : 'li:not(.selectable-disabled)',
    stop: function(){
      var result = '';
      $( ".ui-selected", this ).each(function() {
        result += " #" + ( $(this).index() + 1 );
      }).addClass('selectable-disabled').removeClass('ui-selected');
      $( "#select-result" ).html(result || 'none');
    }
  });
  
  $('#restore').click(function(){
    $('.selectable-disabled').removeClass('selectable-disabled');
  });
});
.selectable-disabled{
  text-decoration : line-through;
  pointer-events : none;
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Selectable - Serialize</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">

    <style>
      #feedback { font-size: 1.4em; }
      #selectable .ui-selecting { background: #FECA40; }
      #selectable .ui-selected { background: #F39814; color: white; }
      #selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
      #selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  </head>
  <body>
    <p id="feedback"><span id="select-result">none</span>.</p>
    <ol id="selectable">
      <li class="ui-widget-content">Item 1</li>
      <li class="ui-widget-content">Item 2</li>
      <li class="ui-widget-content">Item 3</li>
      <li class="ui-widget-content">Item 4</li>
      <li class="ui-widget-content">Item 5</li>
      <li class="ui-widget-content">Item 6</li>
    </ol>
    <p><button id=restore>Restore</button></p>
  </body>
</html>

Answer №2

To turn off the selectable widget, simply use the disable method:

$(this).selectable("disable");

$(function() {
  $("#selectable").selectable({
    stop: function() {
      var result = $("#select-result").empty();
      $(".ui-selected", this).each(function() {
        $(this).css('text-decoration', 'line-through'); // This line adds strike through formatting.
        var index = $("#selectable li").index(this);
        result.append(" #" + (index + 1));
      });
      $(this).selectable("disable"); // http://api.jqueryui.com/selectable/#method-disable
    }
  });
});
#feedback {
  font-size: 1.4em;
}
#selectable .ui-selecting {
  background: #FECA40;
}
#selectable .ui-selected {
  background: #F39814;
  color: white;
}
#selectable {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 60%;
}
#selectable li {
  margin: 3px;
  padding: 0.4em;
  font-size: 1.4em;
  height: 18px;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Selectable - Serialize</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>

<body>
  <p id="feedback"><span id="select-result">none</span>.</p>
  <ol id="selectable">
    <li class="ui-widget-content">Item 1</li>
    <li class="ui-widget-content">Item 2</li>
  </ol>
</body>

</html>

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

Creating a Map in TypeScript from an Array

I have a series of TypeScript objects structured like this: interface MyObject { id: string, position: number } My goal is to transform this array into a map format where it shows the relationship between id and position, as needed for a future JSON ...

Next.js application shows 404 errors when trying to access assets within the public directory

I've been struggling to display the favicon for my site (which uses next.js). Despite going through numerous Stack Overflow posts and tutorials, I'm feeling increasingly frustrated. The structure of my project, particularly the public directory, ...

Launch a fresh fancybox once the previous one has exited

I am currently facing an issue with my password change process through a fancybox window. Whenever a user enters the wrong password, a "Wrong Password" iframe opens up. However, the challenge arises when I try to reopen the "Password Change" iframe after c ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Troubleshooting React child problems in TypeScript

I am facing a coding issue and have provided all the necessary code for reference. Despite trying numerous solutions, I am still unable to resolve it. export class JobBuilderOptimise extends React.Component<JobBuilderOptimiseProps & JobBuilderOptim ...

Maximizing the efficiency of critical rendering path while utilizing bootstrap

Is it feasible to enhance the critical rendering path (like Google and Facebook) while utilizing Bootstrap 3? Facebook opted for inlining styles connected to the header and sidebars. Meanwhile, Google inlined all styles since they have minimal styles for ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

When utilizing document.addEventListener in JavaScript, Firefox fails to report exceptions triggered by DOMContentLoaded

I'm developing an internal framework that must be independent of any external dependencies such as jQuery. I'm working on implementing a custom DOM ready-style functionality, where callbacks in the ready queue should continue executing even if an ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

Capture the incoming path and direct it back after the user logs in

I'm currently facing a challenge with my app that has a login feature and a dashboard with threads. Each thread has its own unique URL address. The issue arises when I want to share the thread URL with someone who is not logged in, as they would need ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

jQuery does not change the scroll position of elements

I'm looking to implement a feature on my website where certain points act as "magnets" and when the user is near one of these points, the window automatically scrolls to the top. I found a jQuery plugin that does something similar which you can check ...

Showing content in a way that spaces out below the text

Could someone assist me with a CSS problem I'm having? I understand CSS, but debugging is not my strong suit. When I use display: inline-block for both my Academic Information and Personal Information, I'm getting extra white space below (above " ...

Node.js Express JS is currently in the process of retrieving a file

I'm currently grappling with an issue while attempting to download a file using express js. Here is the function in question: var download = function(uri, filename, callback) { request .get(uri) .on('response', function (response) { ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...

What is the best way to convert a List of objects to JSON using a dynamic variable?

I have a need to serialize a list of objects in a specific way: Imagine I have the following C# class: public class Test { public string Key; public string Value; } List<Test> tests; When I serialize this list (return Json(tests.ToArray()) ...

Recharge Backbone prior to a lockdown

I'm currently utilizing a script within Backbone in a Cordova application (Android) that causes the app to freeze for 5 seconds, and unfortunately I am unable to find an alternative method. Due to this issue, I would like to display a loading message ...

Ways to effectively store continuous scale data in a database

I am currently running a straightforward Node.js server (using Express) on my local machine on port 8000. By utilizing the npm package serialport, I have successfully connected to a scale and am able to retrieve its weight in a continuous manner as shown ...

Converting a jQuery DOM element into a string representation

Currently, I am working with a textarea that contains the contents of an HTML file. This textarea includes all elements of my HTML page such as doctype, head, html, etc. My goal is to save the content of the textarea into a DOM variable using $.parseHTML: ...