Reposition the checked box to the top of the list

My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked.

Below is the code snippet:

<script>
  let newData = [
    {
      Id: '1',
      Name: 'a',
      Group: 'GroupA'
    },
    {
      Id: '2',
      Name: 'b',
      Group: 'GroupB',
      selected: false
    },
    {
      Id: '3',
      Name: 'c',
      Group: 'GroupC'
    },
    {
      Id: '4',
      Name: 'd',
      Group: 'GroupD'
    },
    {
      Id: '5',
      Name: 'e',
      Group: 'GroupA'
    },
    {
      Id: '6',
      Name: 'f',
      Group: 'GroupA'
    },
    {
      Id: '7',
      Name: 'g',
      Group: 'GroupB'
    },
    {
      Id: '8',
      Name: 'h',
      Group: 'GroupC'
    }
  ];

  // Separate the data by Group
  let groupData = {};
  newData.forEach((item) => {
    const { Group } = item;
    if (!groupData[Group]) {
      groupData[Group] = [];
    }
    groupData[Group].push(item);
  });

  // Function to handle checkbox click
  function handleCheckboxClick(item) {
    item.selected = !item.selected;

    // Move selected item to the top of its Group list
    const Group = item.Group;
    const index = groupData[Group].findIndex((data) => data.Id === item.Id);
    groupData[Group].splice(index, 1);
    groupData[Group].unshift(item);
  }
</script>

{#each Object.keys(groupData) as Group}
  <h3>{Group}</h3>
  <div>
    {#each groupData[Group] as item}
      <label>
        <input
          type="checkbox"
          bind:checked={item.selected}
          on:click={() => handleCheckboxClick(item)}
        />
        {item.Name}
      </label>
    {/each}
  </div>
{/each}

<style>
  h3 {
    margin-top: 20px;
  }

  div {
    display: flex;
    flex-direction: column;
  }
</style>

https://stackblitz.com/edit/node-cjqvpz?file=src%2Froutes%2F%2Bpage.svelte

Answer №1

If you want to achieve this layout without relying on the Svelte framework or Javascript, it can be done simply with pure HTML and CSS:

div { display: flex; flex-direction: column; }
label:has(input:checked) { order: -9999; }
<h3>Topic</h3>
<div>
  <label> <input type=checkbox> q </label>
  <label> <input type=checkbox> w </label>
  <label> <input type=checkbox> e </label>
</div>
<h3>Topic</h3>
<div>
  <label> <input type=checkbox> r </label>
  <label> <input type=checkbox> t </label>
  <label> <input type=checkbox> y </label>
</div>
<h3>Topic</h3>
<div>
  <label> <input type=checkbox> u </label>
  <label> <input type=checkbox> i </label>
  <label> <input type=checkbox> o </label>
</div>

You can utilize display:flex on the parent containers of the checkboxes and apply order:-99999 to adjust their order within the flex layout.

This approach demonstrates the clever use of :has to target the label containing the checkbox rather than the checkbox itself, ensuring styling is applied correctly.

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

Intersecting realms document

Currently I am working on a web store using Magento Go. Unfortunately, this platform does not support server side scripting languages such as PHP. Despite this limitation, I still need to save order data post successful checkout and share it with my shippi ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

Validating phone numbers using AngularJS

Seeking validation for phone numbers based on specific conditions: - If all 10 digits are identical, show an error message. - If it begins with the number 1, display an error message. Have you encountered a similar scenario? Please share your sug ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

Troubleshooting Problems with CSS Three-Column Layout

Struggling with aligning domain names in a 3 column setup, I have been attempting this for some time now without success. I am new to this and could use some guidance. Here is the code: TPL file <div> <p class="center">{foreach key=num it ...

What is the best way to position my header at the top of my navigation bar?

I am new to the world of HTML and CSS! My goal is as follows: https://i.stack.imgur.com/hmLNS.png This is my progress so far: https://i.stack.imgur.com/rav8P.png I am also looking to have the header fill the entire browser window and remain fixed, wit ...

Querying a document by its Id using only JSON in MongoDB

I am trying to query a document in Mongodb (2.6.1) using pure JSON without using ObjectIds. According to the mongodb extended json documentation, I expected the code db.collection.findOne({"_id": {"$oid": "51b6eab8cd794eb62bb3e131"}}) to work but it is th ...

Updating specific data in MongoDB arrays: A step-by-step guide

{ "_id":{"$oid":"5f5287db8c4dbe22383eca58"}, "__v":0, "createdAt":{"$date":"2020-09-12T11:35:45.965Z"}, "data":["Buy RAM","Money buys freedom"], & ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

How to customize the arrow color of tooltips in Bootstrap 4

After spending an hour searching online, I still can't figure out how to change the tooltip arrow color to red. None of the code snippets I found seem to work for me. My latest attempt was: .tooltip-arrow { border-right-color: red; border-left-c ...

The presence of inline display causes gaps of white space

Located at the bottom of this webpage is a media gallery. The initial three images comprise the photo gallery, followed by video thumbnails inlined afterwards. However, there seems to be an issue with the alignment of each element within the video gallery. ...

Error message: "NAN encountered while attempting to extract a numerical value from

I've encountered a strange bug in my coding. I'm working on a weather forecasting website that uses geolocation to identify your city and then utilizes the wunderground API to provide the forecast. The issue arises when manually searching for a c ...

React error: The module "react-router-dom" does not have a member named "useNavigate" available for export

I'm attempting to include useNavigate for use as outlined in the top answer here: react button onClick redirect page import { useNavigate } from "react-router-dom"; However, I am encountering this error: export 'useNavigate' (impo ...

I am interested in displaying the PDF ajax response within a unique modal window

With the use of ajax, I am able to retrieve PDF base64 data as a response. In this particular scenario, instead of displaying the PDF in a new window, is it possible to display it within a modal popup? Any suggestions on how this can be achieved? $.ajax ...

However, when it comes to the jQuery dropdown menu, the submenus open inwards rather than extending

I recently developed a jQuery menu that includes dropdowns. However, I encountered an issue where the subMenu items do not open to the left when hovered over. Despite my attempts to adjust the position using CSS properties such as absolute or relative posi ...

Struggling to showcase array data in a visually appealing table format?

Hello, I am currently facing the following issue Here is a snapshot of my current website; https://i.sstatic.net/pNXNx.png I am trying to display content in a table from an array stored in a JSON file. Initially, I used a foreach loop which worked perfe ...

The issue of a non-firing Ajax click event in a JavaScript file

I have set up a table in JSP and am attempting to trigger a function when clicking on the table rows to post the data. I created a JavaScript file with an ajax click event, but unfortunately, the event is not being fired. $(document).ready(function( ...

Loop through the coefficients of a polynomial created from a string using JavaScript

Summary: Seeking a method to generate a polynomial from specified coordinates, enabling coefficient iteration and optional point evaluation I am currently developing a basic JavaScript/TypeScript algorithm for KZG commitments, which involves multiplying c ...