Функция FixedColumn не применяется в данных DataTableJavascript

Форум по Javascript
Ответить
Anonymous
 Функция FixedColumn не применяется в данных DataTable

Сообщение Anonymous »

Я пытаюсь заморозить первые четыре столбца этого данных, когда пользователь прокручивает его. Но стиль «dtfc-has-left» style = «позиция: относительно;« »не применяется, когда я осматриваю дат в браузере, и эта функция не работает. В случае, если я что-то упускаю, я добавляю почти весь код здесь. Пожалуйста, дайте мне знать, если кто-то может увидеть причину, почему замороженные колонки не применяются.
[*]






Select a tender to add a new estimation. Only eligible tenders are shown in the dropdown below.



All Tenders' Estimations


@foreach (var item in ViewBag.Tenders as List)
{

@item.Text

}


@if (Model == null || !Model.Any())
{
No Estimations Available At this Time.
}
else
{


Toggle Columns

@*
Toggle Columns
*@
  • Select All



@* class="table-responsive mx-auto" style="overflow-x: auto; width: 100%;" *@







@foreach (var estimation in Model)
{


@{
var status1 = (EstimationStatusEnum)estimation.EstimationStepStatus;

string actionName = status1 switch
{
EstimationStatusEnum.PileSetupPending => "EstimationPileWizard",
EstimationStatusEnum.ValuationPending => "EstimationValWizard",
EstimationStatusEnum.SubmissionPending => "EstimationSubmissionWizard",
EstimationStatusEnum.ResultPending => "EstimationResultWizard",
EstimationStatusEnum.ResultSubmitted => "EstimationResultWizard",
_ => null
};

bool isReview = status1 == EstimationStatusEnum.ResultSubmitted;
if (!string.IsNullOrEmpty(actionName))
{
if (isReview || estimation.EstimationStatus == false)
{

Review

}
else
{

Proceed

}
}
}

@estimation.EstID
@estimation.EstRefID
@estimation.TenderProjName

@{
var status = (EstimationStatusEnum)estimation.EstimationStepStatus;
var stepLabels = new Dictionary
{
{ EstimationStatusEnum.PileSetupPending, ("Pile Setup Pending", "info") },
{ EstimationStatusEnum.ValuationPending, ("Valuation Pending", "primary") },
{ EstimationStatusEnum.SubmissionPending, ("Submission Pending", "success") },
{ EstimationStatusEnum.ResultPending, ("Result Pending", "secondary") },
{ EstimationStatusEnum.ResultSubmitted, ("Completed", "dark") }
};

var (label, badgeClass) = stepLabels[status];
}
@label


@{
string result = estimation.Result?.ToString() ?? "";
string displayText = result;
string resultBadgeClass = result switch
{
"Won" => "success",
"Lost" => "danger",
"In Abeyance" => "warning",
"Cancelled" => "secondary",
_ => "info"
};

if (string.IsNullOrWhiteSpace(result) || !new[] { "Won", "Lost", "In Abeyance", "Cancelled" }.Contains(result))
{
displayText = "NAY";
}
}
@displayText


@if (estimation.EstimationStatus == true)
{

@estimation.ChangeRequestCount

}
else
{
@estimation.ChangeRequestCount
}

@estimation.CompanyName
@($"{estimation.CompPhoneCode} {estimation.CompPhone}")
@estimation.CompEmail
@estimation.RepFirstName @estimation.RepLastName
@($"{estimation.RepPhoneCode} {estimation.RepPhone}")
@estimation.RepEmail

@(estimation.ClientBudget == 0.00M ? "Not Provided" : estimation.ClientBudget.ToString("#,0.00"))


@((estimation.MaterialValue == null || estimation.MaterialValue == 0.00M)
? "NAY"
: estimation.MaterialValue?.ToString("#,0.00"))


@((estimation.TenderValue == null || estimation.TenderValue == 0.00M)
? "NAY"
: estimation.TenderValue?.ToString("#,0.00"))


@((estimation.MarkUpPercentage == null || estimation.MarkUpPercentage == 0.00M)
? "NAY"
: estimation.MarkUpPercentage?.ToString("F2"))


@((estimation.EstimatedDurationDays == null || estimation.EstimatedDurationDays == 0.00M)
? "NAY"
: estimation.EstimatedDurationDays?.ToString("F2"))

@estimation.TenderReceiptDate.ToShortDateString()
@estimation.TenderDueDate.ToShortDateString()
@(estimation.SubmissionDate?.ToShortDateString() ?? "-")
@estimation.EstFirstName @estimation.EstLastName
@estimation.TLFirstName @estimation.TLLastName
@(estimation.EstResReceivedDate?.ToShortDateString() ?? "-")
@estimation.WonCompName
@estimation.SuccessPrice?.ToString("#,0.00")


@estimation.EstFeedback


@estimation.EstContractRefID

@if (estimation.EstimationStatus == true)
{
Active
}
else
{
Inactive
}



@if (estimation.HasSoilProfile)
{

View Soil Profile

}


@if (estimation.HasPileReq)
{

View Pile Setup

}



}



@* Modal to view soil profile *@








@* Modal to view requested pile *@








}


.dataTables_wrapper .dataTables_scroll {
overflow: auto;
}

th, td {
white-space: nowrap;
}

.dt-button {
margin-right: 5px;
}

.estimation-link:hover {
background-color: lightgreen !important;
color: black !important;
}

.change-request-link:hover {
background-color: #e91e63 !important;
color: black !important;
}

/* Initially hide optional columns */
th.toggle-optional,
td.toggle-optional {
display: none;
}

/* Add here */
#columnVisibilityOptions {
max-height: 250px;
overflow-y: auto;
overflow-x: hidden;
padding-right: 10px;
}

.div1 th {
background: #198754 !important;
}


@section Scripts {








$(document).ready(function () {

// Setup filter for Active Inactive Status
let statusFilterValue = '';

$.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
if (!statusFilterValue) return true;

const row = settings.aoData[dataIndex].nTr;
const status = $('td:eq(28)', row).data('status');
return status === statusFilterValue;
});

// Export file title setup
var now = new Date();
var formattedDateTime = now.toLocaleString('en-GB', {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
}).replace(/[/:]/g, '-').replace(',', '');

var exportTitle = 'Estimation Master List - Exported Date Time: ' + formattedDateTime;
var exportFileName = 'Estimation_Master_Export_ ' + formattedDateTime;

// Tender status dictionary
const tenderStatuses = @Html.Raw(Json.Serialize(ViewBag.TenderStatuses));

function updateAddEstimationButtonVisibility() {
const selectedTenderId = $('#tenderSelect').val();
const addBtn = $('#addEstimationBtn');

// If "All Tenders" (value 0) is selected, hide the button
if (selectedTenderId === "0") {
addBtn.hide();
return;
}

// Convert selectedTenderId to a number for lookup
const tenderIdNum = parseInt(selectedTenderId, 10);
const status = tenderStatuses[tenderIdNum]; // Look up using the numeric ID

if (status === true) {
addBtn.show();
} else {
addBtn.hide();
}
}

// --- Event Handlers ---

// Handle Tender Dropdown Change
$('#tenderSelect').on('change', function () {
const selectedValue = $(this).val();
const url = selectedValue === "0"
? "/Estimation/Index"
: `/Estimation/Index?tenderID=${selectedValue}`;
window.location.href = url;
});

// Handle Add Estimation Button Click
$('#addEstimationBtn').on('click', function () {
const selectedTenderId = $('#tenderSelect').val();
if (!selectedTenderId || selectedTenderId === "0") {
alert("Please select a valid Tender to create an estimation.");
return;
}
window.location.href = `/Estimation/EstimationCreateWizard?tenderID=${selectedTenderId}&estID=0`;
});

// --- Initializations ---

// Initial check on page load to set button visibility
updateAddEstimationButtonVisibility();

// Initialize DataTable if table exists
if ($('#estimationTable').length > 0) {
let $filterRow = $('');
$('#estimationTable thead tr:eq(0) th').each(function () {
$filterRow.append('');
});
$('#estimationTable thead').append($filterRow);

var table = $('#estimationTable').DataTable({
dom: 'lfrtipB',
buttons: [
{
extend: 'csvHtml5',
text: '
Export CSV',
className: 'btn btn-sm btn-secondary export-btn',
title: exportTitle,
filename: exportFileName,
exportOptions: {
columns: function (idx, data, node) {
var columnCount = table.columns().count();
return $(node).is(':visible') && idx !== 0 && idx !== columnCount - 2 && idx !== columnCount - 1;
},
modifier: { search: 'applied', order: 'current' }
}
},
{
extend: 'excelHtml5',
text: ' Export Excel',
className: 'btn btn-sm btn-secondary export-btn',
title: exportTitle,
filename: exportFileName,
exportOptions: {
columns: function (idx, data, node) {
var columnCount = table.columns().count();
return $(node).is(':visible') && idx !== 0 && idx !== columnCount - 2 && idx !== columnCount - 1;
},
modifier: { search: 'applied', order: 'current' }
}
}
],
scrollX: true,
scrollY: '500px',
fixedColumns: {
leftColumns: 4
},
scrollCollapse: true,
paging: true,
//fixedHeader: true,
orderCellsTop: true,
order: [[1, 'asc']],
columnDefs: [
{
targets: [13, 14, 15, 16, 17, 25], // Client Budget, Material Value, Tender Value, MarkUp %, Estimated Duration (Days), Success Price
render: function (data, type, row) {

if (type === 'filter' || type === 'sort') {
let cleanData = data.toString().replace(/£/g, '').replace(/,/g, '');
if (cleanData === "NAY" || cleanData === "Not Provided" || cleanData.trim() === "" || isNaN(parseFloat(cleanData))) {
return -Infinity;
}
return parseFloat(cleanData);
}
// For display, return the data as is (with commas)
return data;
},
type: 'num-fmt'
// targets: [12,13,14,24],
// createdCell: function (td, cellData) {
// var plainText = cellData ? cellData.toString().trim() : "";
// $(td).html('' + plainText + '' + plainText);
// }
},
{ orderable: false, targets: 0 }
],
initComplete: function () {
var api = this.api();

api.columns().eq(0).each(function (colIdx) {
var cell = $('.filters th').eq(colIdx);
var colHeader = $('#estimationTable thead tr:eq(0) th').eq(colIdx).text().trim(); // For debugging

//console.log(`Column Index: ${colIdx}, Header: "${colHeader}"`);
if (colIdx === 4) {
$(cell).html(`

All
Pile Setup Pending
Valuation Pending
Submission Pending
Result Pending
Completed
`);
}
else if (colIdx === 5) { // Column index for "Result"
$(cell).html(`

All
Won
Lost
In Abeyance
Cancelled
NAY

`);
}
// Active/ Inactive filter
else if (colIdx === 28) {
$(cell).html(`

All
Active
Inactive
`);

$('select', cell).on('change', function () {
statusFilterValue = this.value;
api.draw(); // ⬅ trigger redraw with updated filter
});
}
else if (colIdx !== 0 && colIdx !== 29 && colIdx !== 30 ) { // Not the 'Action' column
$(cell).html('');
}
else { // 'Action' column
$(cell).html('');
}

$('input, select', cell).on('keyup change', function () {
api.column(colIdx).search(this.value).draw();
});
});

}
});
}
});

}


Подробнее здесь: https://stackoverflow.com/questions/796 ... -datatable
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»