Issues with alignment in Bootstrap Table columns

I'm facing an issue with formatting a table properly. Despite adjusting the colspans, I can't seem to get it right. There's an additional column header on the right labeled "Operations" that is extending outside the div, making it impossible to scroll to it. Moreover, none of the rows match their headers. What could be the reason behind this problem?

https://i.sstatic.net/Fla3v.png

javascript

<script>
  var $table = $('#table')
  var $remove = $('#remove')
  var selections = []
    document.getElementById("Add").onclick = function () {
        location.href = "new.php";
    };

// Add more JS code

</script>

HTML format for table insertion

<table
  id="table"
  data-toolbar="#toolbar"
  // Add more table properties            
  <thead>
        <tr>
        <tr>         
        // Add table headers          
        </tr>                       
        </tr>
        </thead>
</table>                           

EDIT: Interestingly, when zoomed out completely on the page, the table seems to align better. https://i.sstatic.net/8GBZ7.png

Answer №1

After running your HTML through the validator.nu, I found a semantic issue related to missing cells in the thead section.

Addition of a tbody with trs and tds that correspond to the thead is necessary for proper alignment. While there are JavaScript errors present, I did not investigate them further.

You had incorrectly nested a table row (tr) within another tr, which I have corrected by removing the redundant one.

By rectifying the HTML structure, the table functions as intended:

 var $table = $('#table')
  var $remove = $('#remove')
  var selections = []
    document.getElementById("Add").onclick = function () {
        location.href = "new.php";
    };

  function getIdSelections() {
    return $.map($table.bootstrapTable('getSelections'), function (row) {
      return row.id
    })
  }

  function responseHandler(res) {


    $.each (res.rows, function (i, row) {
      row.state = $.inArray(row.id, selections) !== -1
    })
    return res
  }

  function detailFormatter(index, row) {
    var html = []
    $.each(row, function (key, value) {
      html.push('<p><b>' + key + ':</b> ' + value + '</p>')
    })
    return html.join('')
  }

function operateFormatter(value, row, index) { 
return [
 '<a class="remove" onclick="return confirm(\'Are you sure you want to delete this vendor?\')" href="deleteVendor.php?vendor_id=' + row.id + '" title="Remove">', 
'<i class="fa fa-trash"></i>', 
'</a>', '<a class="view" href="viewVendor.php?vendor_id=' + row.id + '" title="View">',
 '<i class="fa fa-eye"></i>', '</a>' ].join(''); }

  window.operateEvents = {
    'click .view': function (e, value, row, index) {
      sessionStorage.setItem("id", row);

    },

  }

  function totalTextFormatter(data) {
    return 'Total'
  }

  function totalNameFormatter(data) {
    return data.length
  }

  function totalPriceFormatter(data) {
    var field = this.field
    return '$' + data.map(function (row) {
      return +row[field].substring(1)
    }).reduce(function (sum, i) {
      return sum + i
    }, 0)
  }

  function initTable() {
    $table.bootstrapTable('destroy').bootstrapTable({

      height: 700,
      locale: $('#locale').val(),
      columns: [
        [{
          field: 'state',
          checkbox: true,
          rowspan: 2,
          align: 'center',
          valign: 'middle'
        },  {
          title: 'Vendor',
          colspan: 1,
          align: 'center'
        },  {
          title: 'Vendor Details',
          colspan: 8,
          align: 'center'
        }],
        [{
          field: 'name',
          title: 'Vendor',
          sortable: true,
          footerFormatter: totalNameFormatter,
          align: 'center',

        },{
          field: 'account_company',
          title: 'Account Company',
          sortable: true,
          footerFormatter: totalNameFormatter,
          align: 'center',

        }, {
          field: 'id',
          title: 'Vendor ID',
          sortable: true,
          footerFormatter: totalNameFormatter,
          align: 'center',

        },  {
          field: 'residual',
          title: 'Residual Risk',
          sortable: true,
          footerFormatter: totalNameFormatter,
          align: 'center',

        }, 
        {
          field: 'company',
          title: 'Company',
          sortable: true,
          align: 'center',
          footerFormatter: totalPriceFormatter
        },      {
          field: 'type',
          title: 'Type',
          sortable: true,
          align: 'center',
          footerFormatter: totalPriceFormatter
        },{
          field: 'status',
          title: 'Status',
          sortable: true,
          align: 'center',
          footerFormatter: totalPriceFormatter
        },
        {
          field: 'owner',
          title: 'Owner',
          sortable: true,
          align: 'center',
          footerFormatter: totalPriceFormatter
        }, 
        {
          field: 'operate',
          title: 'Operations',
          align: 'center',
          clickToSelect: false,
          events: window.operateEvents,
          formatter: operateFormatter
        },



        ]
      ]
    })
    $table.on('check.bs.table uncheck.bs.table ' +
      'check-all.bs.table uncheck-all.bs.table',
    function () {
      $remove.prop('disabled', !$table.bootstrapTable('getSelections').length)

      // save your data, here just save the current page
      selections = getIdSelections()
      // push or splice the selections if you want to save all data selections
    })
    $table.on('all.bs.table', function (e, name, args) {
      console.log(name, args)
    })
    $remove.click(function () {
      var ids = getIdSelections()
      $table.bootstrapTable('remove', {
        field: 'id',
        values: ids
      })
      $remove.prop('disabled', true)
    })
  }

  $(function() {
    initTable()

    $('#locale').change(initTable)
  })
table {
width: 100%;
}

td {
padding: 1em;
border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<table
  id="table"
  data-toolbar="#toolbar"
  data-search="true"
  data-show-refresh="true"
  data-show-toggle="true"
  data-show-fullscreen="true"
  data-show-columns="true"
  data-show-columns-toggle-all="true"
  data-detail-view="true"
  data-show-export="true"
  data-click-to-select="true"
  data-detail-formatter="detailFormatter"
  data-minimum-count-columns="2"
  data-show-pagination-switch="true"
  data-pagination="true"
  data-id-field="id"
  data-page-list="[10, 25, 50, 100, all]"
  data-side-pagination="client"
   data-url="ajax.php" 
  data-response-handler="responseHandler" >
    <thead>
        <tr>                                                                        
            <td data-field="name">Vendor</td>
            <td data-field="account_company">Account Company</td>
            <td data-field="id">Vendor ID</td>
            <td data-field="residual">Residual Risk</td>
            <td data-field="company">Company</td>
            <td data-field="type">Type</td>
            <td data-field="status">Status</td>
            <td data-field="owner">Owner</td>
        </tr>                       
        </thead>
        <tbody>
          <tr>
            <td>Some data</td>
            <td>Some data</td>
            <td>Some data</td>
            <td>Some data</td>
            <td>Some data</td>
            <td>Some data</td>
            <td>Some data</td>
            <td>Some data</td>
          </tr>
        </tbody>
</table>

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

What is the purpose of defining the initialState in Redux?

As per the Redux documentation, it is considered a best practice to establish an initialState for your reducer. However, maintaining this initialState can become challenging when the state relies on data from an API response, leading to discrepancies betwe ...

AWS Lambda encountered an issue: Task terminated unexpectedly prior to finishing the operation

I've scoured various Stack Overflow threads for solutions to my issue, but no luck so far. As a beginner in this field, I might not be implementing the suggested fixes correctly. Here's my code, and any help would be greatly appreciated. var mys ...

React blogging site's administrative dashboard

https://i.sstatic.net/M6fUJ.png I am currently in the process of developing a blogging platform using MERN technology. Specifically, I am focused on creating a restful API with Node.js, Express, and MongoDB. The frontend, built with React, consists of thr ...

What is the most effective way to organize and display objects, such as using an "interest" attribute that could be the same for multiple "User" objects?

Hey everyone, I'm facing some challenges while trying to create a function. In the code snippet provided, I aim to develop the interestMatch function. The goal of this function is to analyze all users and identify those who share the same interest - s ...

Utilizing razor syntax within JavaScript

I've encountered an issue with the code snippet below. I am trying to check if any content exists in my model and then use a ternary operator to show or hide based on its existence. $(document).ready(function() { (@Model.MyProperties.Any()) ? ...

Angular 2 issue with nested form elements

Looking to build a form that includes nested sub/child components within it. Referring to this tutorial: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 https://plnkr.co/edit/clTbNP7MHBbBbrUp20vr?p=info List of modificatio ...

Do not decode HTML content within an iframe; instead, extract the data directly from the HTML source

To expedite execution time, we have made the decision to not display the table in the iframe as it is invisible to the client. However, we still need to update the main page table by copying its contents. The approach we are taking is that the iframe shou ...

I'm attempting to integrate the map function into my React Redux application, but after implementing useDispatch, I'm encountering an error message in the console

I am currently troubleshooting an app I'm working on, but I keep encountering errors in the console. Included below is a picture of the error as well as the code snippet triggering the issue. Can anyone provide insight into what might be causing this ...

Exploring the capabilities of the VSCode Volar extension in a project utilizing Vue 2, Nuxt, Typescript, and the @nuxtjs composition-api

Trying to set up the Volar VSCode extension for a NuxtJS / Typescript project and facing two issues in .vue file templates. Followed the installation guide for Vue 2 and Typescript, and enabled Take Over mode. Solved some codebase issues with the extensio ...

Error converting object to array

I recently created a function to transform an object into an array. Function: function convertObjectToArray(obj) { const result = []; for (const [key, value] of Object.entries(obj)) { if (typeof value === 'object' && ...

Polymer Google Maps Marker OnClick Function

I am struggling to trigger a click event for a google maps marker while utilizing the Polymer web component. After reviewing this question on Stack Overflow, I have noticed a minor difference in my code that may be causing issues. My implementation invol ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Efficiently Loading JavaScript Files in Django for Optimal Website Performance

I have a Django blog app with a Post model that includes a field called body. This field may contain Latex, so I utilize MathJax.js, as well as code snippets, for which I use highlight.js. Sometimes I use both, and other times neither. Is there a way to a ...

how to open a new tab using JavaScript with Selenium

My code is supposed to open a new window that goes from the login window to the main menu, module, reports, and finally the report name. The report name should be opened in the next tab. Issue: The report name is not opening in a new tab; it's openin ...

What is the best way to obtain a direct file link from a server URL using JavaScript?

After acquiring a file located at /home/johndoe/index.html, I am utilizing a tool like XAMPP to host, with the folder /home being hosted on localhost. The variables in play are as follows: $server_addr = "localhost"; $server_root = "/home"; $file_dir = " ...

Display the value of a shortened string

My Goal I aim to develop a method for determining the amount of a string visible before it gets cut off. Motivation In my project, there is a collection of items that can be chosen. A panel presents a concatenated string of the selected item names separa ...

Transform an array into an object utilizing only underscore

I'm currently learning about underscore and came across a task that I could use some assistance with. I have an array containing objects like the following: [ // ... { "type": "presence", "params": { "i ...

Encountering question marks while attempting to retrieve data from the API

I have developed an application using node-webkit that notifies me whenever there is an alarm in my country due to the ongoing war. There is a particular website that provides a JSON file containing information about current alerts. However, when I attem ...

Accessing a variable outside of the component constructor will result in the variable being

Currently, I am tackling a project that involves React and Electron. However, I have encountered an error that is causing some confusion. The issue revolves around a component with a constructor that receives props in the form of two variables. This constr ...