Is there a way to enable multiple selections in a particular section?

Currently, I am in the process of working on my step by step order and I want to express my gratitude for all the assistance I have received so far. Despite the help, I still have some unanswered questions!

The steps in my project are categorized into different <section>, and I would like to assign a class="multiple" to one specific <section> so that multiple selections can be made within it. The use of .selected helps me determine whether an <li> has been selected or not.

This is the code I am currently working with:

$('li').on('click', function(e) {
   e.preventDefault();
   // remove selected class from links after the current one
   $(this).closest('section').nextAll('section').find('li').removeClass('selected');
   // remove selected from siblings, toggle current selected class
   $(this).siblings('li').removeClass('selected').end().toggleClass('selected');
   var $target = $('#' + $(this).attr('data-id'));
   if ($target.length) {
       // hide any steps after the current one that may be shown
       $(this).closest('section').nextAll('section').find('.step').not($target).removeClass('active');
       // toggle display of selected step
       $target.toggleClass('active', $(this).hasClass('selected'));
   } else {
       console.log('do something else to end this thing');
   }
})

Hence, my query involves exploring possibilities within my code to enable the <section class="multiple"> functionality, which allows for multiple items to be selected.

I have shared my JSFiddle here. Feel free to click on the items to view the last step, specifically focusing on the section that permits multiple selections.

I appreciate your support in advance. Thank you!

Answer №1

Make sure to first check for the presence of the .multiple class before proceeding to remove the .selected class from the menu items (li). https://jsfiddle.net/979aL2g5/7/

$('li').on('click',function(e) {
  e.preventDefault();
  var $parent = $(this).closest('section')
  // Remove the 'selected' class from links coming after the current one
  $parent.nextAll('section').find('li').removeClass('selected');
  // Remove 'selected' class from siblings and toggle the current 'selected' class
  $(this).toggleClass('selected');
  (! $parent.hasClass('multiple')) && $(this).siblings('li').removeClass('selected');
  var $target = $('#'+$(this).attr('data-id'));
  if ($target.length) {
    // Hide any steps that come after the current one which might be displayed
    $parent.nextAll('section').find('.step').not($target).removeClass('active');
    // Toggle display of the selected step
    $target.toggleClass('active', $(this).hasClass('selected')); 
  } else {
    console.log('Perform some other action to terminate this process');
  }
})
body { color: #333; }
h1 {
  font-size: 20px;
}
.step {
  display: none;
}
.active {
  display: block;
}
selected {
  background: #27ae60 !important;
  color: #fff !important;
}
ul {
  padding:0;
}
li {
  list-style: none;
}
.bananas {
  padding: 20px;
  color: #7f8c8d;
  background: #ecf0f1;
  display: inline-block;
  border-radius: 10px;
  cursor: pointer;
  width: 25%;
  text-align: center;
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 5px;
}
.bananas.special.selected {
  background: #3498db !important;
}

.hi {
  color: #27ae60;
  border-bottom: 2px dotted #27ae60;
}
h1 {
  margin-top: 30px;
  margin-bottom: 30px;
}
.hi.special {
  border-bottom: 2px dotted #3498db;
  color: #3498db;
}

#same_target {
  margin-top: 30px;
  background: #9b59b6;
  padding: 20px;
  color: #fff;
}

#same_target p {
  margin-bottom:0;
}

.nomarking {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="container">
  <section>
    <h1>Begin with the initial step, select an option</h1>
    <ul>
        <li class="bananas nomarking" data-id="one">
          Sprite
        </li>
        <li class="bananas nomarking" data-id="two">
          King Kong
        </li>
        <li class="bananas nomarking" data-id="three">
          Astronauts
        </li>
      </ul>
  </section>

  <section>
    <div id="one" class="step">
    <h1>Select another option for <span class="hi">Sprite</span> in the next step</h1>
      <ul>
        <li class="bananas nomarking" data-id="third">
          McDonalds
        </li>
        <li class="bananas nomarking " data-id="third">
          Burger King
        </li>
        <li class="bananas nomarking" data-id="third">
          Tim Hortons
        </li>
      </ul>
    </div>

    <div id="two" class="step">
      <h1>Select another option for <span class="hi">King Kong</span> in the next step</h1>
      <ul>
        <li class="bananas nomarking" data-id="third">
          McDonalds
        </li>
        <li class="bananas nomarking" data-id="third">
          Burger King
        </li>
        <li class="bananas nomarking" data-id="third">
          Tim Hortons
        </li>
      </ul>
    </div>

    <div id="three" class="step">
      <h1>Select another option for <span class="hi">Astronauts</span> in the next step</h1>
      <ul>
        <li class="bananas nomarking" data-id="third">
          McDonalds
        </li>
        <li class="bananas nomarking" data-id="third">
          Burger King
        </li>
        <li class="bananas nomarking" data-id="third">
          Tim Hortons
        </li>
      </ul>
    </div>
  </section>

  <section class="multiple">
    <div id="third" class="step">
      <h1>Multiple selections allowed in the <span class="hi special">selections</span> section - choose below</h1>
      <ul>
        <li class="bananas special nomarking">
          Hamburger
        </li>
        <li class="bananas special nomarking">
          Coffee
        </li>
        <li class="bananas special nomarking">
          Stackoverflow
        </li>
        <li class="bananas special nomarking">
          Australia
        </li>
        <li class="bananas special nomarking">
          Oldschool
        </li>
        <li class="bananas special nomarking">
          Deadpool
        </li>
      </ul>
    </div>
  </section>
</div>

Answer №2

Out of the various options available, I favor these two methods:

  1. To handle previous sections differently, designate them with class="single" and create two distinct functions. One function can be activated by

    $('li .single').on('click',function(e)...
    , while the other can be triggered by
    $('li .multiple').on('click',function(e)...
    . You already have the first function in place. Modify the second function to remove
    $(this).siblings('li').removeClass('selected')
    so that multiple items can be selected.

  2. The second approach involves maintaining the single '$('li .single').on('click',function(e)...' but incorporating conditional actions within an IF/THEN statement to determine if the user clicked on a single or multiple section. In this case as well, refrain from executing

    $(this).siblings('li').removeClass('selected')
    when inside the .multiple section.

Answer №3

If I were to make a modification:

// remove selected from siblings, toggle current selected class
$(this).siblings('li').removeClass('selected').end().toggleClass('selected');

I would update it to the following code:

// remove selected from siblings if not multiple
if (!$(this).closest('section').hasClass('multiple')) {
    $(this).siblings('li').removeClass('selected');
}
// toggle current selected class
$(this).toggleClass('selected');

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

Execute an asynchronous function in Javascript, then output the returned data to the console

Is there a way to effectively handle the data returned from an async function? example: JS FILE: async function getData(){ try { $.getJSON('./data.json', (data) => { return data; }); } catch(error ...

Is it possible to modify an HTML element when hovering over it in an ASP.Net page?

Is there a way to use jQuery to show the child span text - SomeClassChild3 string when hovering over the parent div - SomeClassParent in an aspx page? Here is the JavaScript section of the code: function ShowDiv(Somedata){ for(var v in Somedata){ va ...

When conditions are met, all items are added to the array

In my Angular app, I have a user list that I am trying to filter based on the condition age > 45. However, all users are being pushed into the validForScheme array instead of just those meeting the condition. I am unable to figure out what is going wron ...

The color overlay for the class label map segmentation in AMI JS is not appearing as expected

I came across this example in vanilla JavaScript. In my project using Angular 7.3.8 with AMI version 0.32.0 (ThreeJS 0.99.0), I imported everything as an angular provider service. When trying the test examples from the provided link, I noticed that the o ...

Enhance Your Vue.js 2.0 Experience: Implementing Vue Components Generated with v-html and Compiling the Markup

Currently Utilizing VueJS 2.0 I am looking to transform the following into a clickable link. Is this possible? This is my vue component: <template> <div v-html="markup"></div> </template> <script> new Vue({ data() { ...

What is the reason that PHP has the ability to set Cookies but Local Storage does not?

Let's take a step back to the era of cookies, not too far back since they are considered old but still quite relevant. PHP allows you to set and read them even though they are a client-side technology; however, JavaScript can also be used completely o ...

How can I use CSS to customize the appearance of the elements within an iframe?

<iframe src="#link"> #document <!doctype html> <html> ... </html> </iframe> Is there a way to customize the styling of elements within the #document using CSS only, without needing to use Jquery? ...

Create a navigation bar using CSS that is designed from an unordered list without any specific

Is it possible to create a multilevel menu using only CSS for the menu structure mentioned below? Websites like cssmenumaker.com showcase examples of menus with 2-3 level submenus by adding classes like has-submenu. Can we achieve this without adding any ...

Google/StackExchange Menu Tab

I am interested in creating a navigation bar similar to Google's or StackExchange's new one, where it is always positioned at the top. It does not need to be fixed there, but I would like it to have links only. How can I achieve this layout with ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

Having issues with ReactJS - function not functioning properly when invoked within componentDidMount() and componentDidUpdate() lifecycle methods

I have encountered an issue that has left me puzzled, and I'm hoping someone can provide some guidance on how to solve it. The task at hand involves implementing a function that adds .active classes to li elements within a navigation bar if they cont ...

CSS: Preserve HTML elements and only conceal the text within an <a> tag

Inside an "a" element, there's an image followed by text as a link. I'm looking to only hide the text of the link without affecting the display of the image. <a href="https://www.example.com/page"> <img src=" ...

How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor: function displayCursorCoordinates(e) { var x = event.clientX; var y = event.clientY; var coordinates = "(" + x + ", " + y + ")"; document.getEl ...

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

Can asynchronous programming lead to memory leakage?

I'm wondering about the potential for memory leaks in asynchronous operations, specifically within Javascript used on both frontend and backend (node.js). When the execute operation is initiated, a delegate named IResponder is instantiated. This dele ...

Linking functions as needed

I apologize for the not-so-great title of this question. Basically, I have a library that generates users with predetermined capabilities. Currently, it involves creating a new user instance and calling asynchronous methods like: var User = require(...).U ...

Having trouble getting the alert text on the left side of a Bootstrap button with the alert class

Hey there, I managed to create two buttons aligned on opposite sides of my webpage - one on the left and one on the right. Each button, when clicked, displays an alert text on its corresponding side, similar to what you see in this picture https://i.sstati ...

What is the best way to vertically center a column of images on mobile devices in a responsive manner?

Currently, I am developing an application that showcases the 9 newest photos with a specific tag. To ensure consistency in image sizes, I have set each photo to be 240px wide and 200px tall. My query now is how can I vertically center these images so they ...

What could be causing my AJAX request to fail?

I've encountered a strange issue with my AJAX call to a PHP file. The call is successfully saving data to the database, but it triggers the error alert instead of the success alert when it returns. Here is the AJAX code from my JavaScript file: $.aja ...