How can I assign a distinct identifier to checkboxes that align with their respective row numbers (update: or item ID) using Bootstrap 4?

I am currently working on designing a table for displaying transaction history related to baby items as part of my javascript course. I need help with assigning each checkbox a unique ID that corresponds to the row number in a sequential order.

Here is the wireframe design:

https://i.sstatic.net/6JVp2.png

Each row in the table is numbered from 1 to the end, and in the rightmost column, there is a toggle checkbox using Bootstrap 4. This allows users to manually select whether they want to list their item for sale ('listing') or end the sales ('ended').

To ensure uniqueness, I plan to name each checkbox input-id 'toggle1', 'toggle2', etc., based on their respective row numbers. The challenge lies in auto-generating these id numbers dynamically.

In order to automatically generate the ids, I have successfully implemented a code snippet that assigns row numbers to the table rows:

Here is a simplified version of the HTML and JavaScript code snippets used:

<table id="table" data-toggle="table" data-height="800" data-pagination="true" data-page-size="3">
    <thead>
        <tr>
            <th data-field="seq-number" data-width="100" data-width-unit="px">Number</th>
        </tr>
    </thead>
</table>
var table = document.getElementsByTagName('table')[0],
rows = table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText';

for (var i = 1, rowlength = rows.length; i < rowlength; i++) {
   rows[i].children[0][text]= i;
}

In addition to this, the code for the table structure and checkboxes has been set up as follows:

<table id="table" data-toggle="table" data-height="800" data-pagination="true" data-page-size="3">
    <thead>
        <tr>
            <th data-field="status" data-width="200" data-width-unit="px">Status</th>
        </tr>
    </thead>

    <tr>
        <td>
            <input type="checkbox" id="toggle1" data-width="100">
                <script>
                     $(function () {
                         $('#toggle1').bootstrapToggle({
                             on: 'Listing',
                             off: 'Ended'
                         });
                     })
                </script>
        </td>
    </tr>

The goal is to have the input id generated and assigned automatically, matching the corresponding row number.

Your suggestions are greatly appreciated.

Update: @cengiz sevimli mentioned that it might be more prudent to assign the status checkbox id with the item ID instead of row numbers for greater uniqueness. However, the question remains on how to create an id combining user ID #000001 with timestamp - such as 000001-201910301600?

Answer №1

It's not necessary to assign a unique id to every checkbox; the required information can be extracted directly from the html within the chosen row.

However, if you prefer to have ids for selected items (which will be submitted with your form), you can assign an id to each input in the table (excluding the selectAll option):

$(".cb input").each(
  (index, el) => {
    // Ensure it's not the "Select All" checkbox
    if($(el).attr("name") === "btSelectItem") {
      // Determine the ID
      let newId = $(el).closest("tr").find(".number").text();
      // Assign the ID to the current checkbox
      $(el).prop("id", newId);
    }
  }
)

To simplify checkbox selection in your table, consider adding a class to the checkbox column (e.g., class="cb"):

<th data-field="cb" data-checkbox="true" class="cb" />

As shown above, you can attach a change event listener to inputs under elements with class="cb".

Here's a complete example:

var $table = $('#table');
var mydata = 
[
    {
        number: 1,
        id: "Item 1",
        name: "Name 1"
    },
    {
        number: 2,
        id: "Item 2",
        name: "Name 2"
    },
    {
        number: 3,
        id: "Item 3",
        name: "Name 3"
    }
];

$(function () {
    $('.table').bootstrapTable({
        data: mydata
    });
    
    $(".cb input").each(
      (index, el) => {
        if($(el).attr("name") === "btSelectItem") {
          let newId = $(el).closest("tr").find(".number").text();
          $(el).prop("id", newId);
        }
      }
    ).change(
      function() {
        let selected = $(this);
        if(selected.attr("name") === "btSelectItem") {
          console.log("Selected: ", selected.prop("id"));
        }
      }
    );

});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>

<div class="container">
   <div class="row">
      <div class="col-12">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th data-field="cb" data-checkbox="true" class="cb" />
              <th data-field="number" class="number">Number</th>
              <th data-field="id">Item ID</th>
              <th data-field="name">Item Name</th>
            </tr>
          </thead>
        </table>
      </div>
   </div>
</div>

I hope this explanation is helpful. Goodbye!

Answer №2

It is recommended to use class names for styling in this scenario. By creating a class in CSS, you can easily apply it to any HTML element, enhancing the readability, reusability, and flexibility of your code. If you require a JavaScript code snippet that generates unique IDs, refer to the example below:

// Function to generate unique IDs for pseudo-private or protected names.
// Ensures uniqueness compared to other generated strings.
// Complexity prevents accidental duplication when using as private/protected name.
//
// Usage:
// 
//     var privateName = generateID();
//     var obj = { 'public': 'foo' };
//     obj[privateName] = 'bar';
var generateID = function () {
  // Math.random provides unique values due to seeding algorithm.
  // Convert to base 36 (numbers + letters) and extract first 9 characters after decimal.
  return '_' + Math.random().toString(36).substr(2, 9);
};

source: gordonbrander

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

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Retrieving JSON information from a PHP file and saving it as a global variable

Currently, I am in the process of developing a cordova mobile application and my goal is to extract all the data from a PHP page that outputs JSON data. This information will then be stored in a global variable for easy local access. Here is an example of ...

Passing an array from PHP to the DataTables JavaScript library

I am attempting to pass a PHP array to the JS Datatable library for testing purposes. Instead of fetching data from a database, I have simplified my approach. Here is a basic representation of my PHP code: $data_fmt['data'][] = array("TEST"); e ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

Bootstrap 4's mobile breakpoint for ordering elements in the div

In the desktop version, my order is as follows: <div class="row"> <div class="col-md-7"> Content 1 </div> <div class="col-md-5"> Content 2 </div> </div> Is there a way to display Content 2 before Conten ...

What is the best way to reference an object within the Vue data as the value of an item?

If I wanted to incorporate the {{ $t('index-p1') }} value within the title property, how would I do so? items: [ { icon: 'mdi-apps', title: 'Welcome', to: '/' }, For int ...

Feeling lost when it comes to tackling the Data Access Object/Layer in an Express/MongoDB setup?

I currently have an Express application that is integrated with MongoDB. My goal is to decouple my database access from the server layer. However, in trying to achieve this, I've encountered two main approaches: Passing Res as an argument //server.j ...

Return to the initial stage of a multistep process in its simplest form following a setTimeout delay

I recently customized the stepsForm.js by Copdrops and made some modifications. Although everything works well, I'm struggling to navigate back to the initial step (first question) after submitting the form due to my limited knowledge of JavaScript. ...

Bootstrap Select fails to refresh on mobile devices

I'm currently utilizing Bootstrap-select in conjunction with Django for handling multi-select items. While it functions properly on desktop, there seems to be an issue when the native mobile drop-down is activated - the selected values from the dropdo ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

Retrieving data with model.fetch in Backbone.js when the server response is null

In my app, we utilize model.fetch() to retrieve JSON from the server. The render function is triggered when the model undergoes a change and looks like this: if(_.isUndefined(this.model.get("id_number"))){ this.template = initialTemplate; } else if(th ...

What is the best way to prevent elements in the split function from being stored in an array?

Currently, I am attempting to utilize the split() method in Javascript to split elements into an array, a result that I do not desire. My goal is for the elements to be stored as values within an object. var string = "as1234,as5678,as6789"; var result = ...

Steps to make a dropdown menu that showcases all files within a folder using HTML5 and Javascript

I am attempting to implement a dropdown menu that displays all the files currently in a directory. The goal is for the user to be able to click on a file in the list and have the name of that file printed to the console. Here is my current progress: HTML ...

Problems encountered with the functionality of Sidr when using an AngularJS button with ng

Utilizing the Sidr mobile menu alongside AngularJS has been a breeze so far. However, I encountered an issue when trying to include a search bar within the mobile navigation - the button functionality seems to be affected. Interestingly, when I placed the ...

The Adobe Brackets Live Preview feature is currently experiencing difficulty connecting to the Node.js server

I'm encountering an issue while trying to run a Node.js server using Adobe Brackets. When I initiate live preview (with the URL being http://localhost:SOMERANDOMPORT/path/to/file.html), and start the server, typing http://localhost:3000/test into anot ...

Guide on generating virtual nodes from a string containing HTML tags using Vue 3

Investigation I stumbled upon this solution for converting a simple SVG with one path layer into Vue2 vnode list and wanted to adapt it for Vue3. After scouring resources, including the MDN docs, I couldn't find any pre-existing solutions. So, I dec ...

Using a JavaScript variable inside a jQuery string

Does anyone have suggestions for what I may be doing incorrectly here? VIEW DEMO HTML Code <div id="usercurrentccbox"> <div class="cardChoice"> <label for="mastercard"></label> </div> </div> JQUERY Sc ...

Adjusting ng-class depending on a certain condition in the controller

I need help updating ng-class to apply a CSS class with a unique background image. Here is an example of what I am trying to achieve: <button id="search" ng-class="{travel: travel }">Search</button> for(var i = 0; i < arrayLength; i++) { ...

What is the method to trigger a confirmation message from the backend code in ASP.NET?

Hello, I am looking to trigger a client-side JavaScript confirm message from the code-behind in ASP.NET. I need to capture the true or false return value from the confirm message. Currently, I am attempting to do this using the following method, but it s ...

Modify the value of a service from the main controller

I have been researching extensively on how to edit a service value from a nested controller. The issue I am facing is that my child controller needs to update a specific value in a service, and this value must be reflected in the parent controller as well. ...