Управляйте возможностью редактирования столбцов таблицы с помощью плагина JQuery-tabledit условно.Jquery

Программирование на jquery
Ответить Пред. темаСлед. тема
Anonymous
 Управляйте возможностью редактирования столбцов таблицы с помощью плагина JQuery-tabledit условно.

Сообщение Anonymous »

В моем проекте .NET Core мне нужно сделать два столбца таблицы редактируемыми. Я использую плагин JQuery-tabledit, и он работает хорошо. Моя проблема в том, что я хочу, чтобы только один из двух столбцов был доступен для редактирования на основе значения, переданного в строке.
Это моя таблица:

Код: Выделить всё



ID
Categoria
Pezzi
Kg
Costo unitario
ECO contributi
Utente
Data agg.



@foreach (var item in Model.Righe)
{

data-id="@item.Id"
@item.Id
@item.Categoria.Nome
@item.Pezzi
@item.Kg.ToString("#,##0.00")
@item.CostoUnitario.ToString("#,##0.00")
@item.ImportoRiga.ToString("#,##0.00")
@item.UtenteAggiornamento
@item.DataAggiornamento.ToString("dd/MM/yyyy")

}

а это мой JavaScript для инициализации таблицы:

Код: Выделить всё

$(document).ready(function () {
function initAutoTabledit() {
$('table[data-tabledit="true"]').each(function () {
var $table = $(this);

// Raccogli le colonne editabili
var editableColumns = [];
var identifierColumn = null;

// Cerca le colonne configurate con data attributes
$table.find('th').each(function (index) {
if ($(this).data('tabledit-identifier') === true) {
identifierColumn = index;
}

if ($(this).data('tabledit-editable') === true) {
editableColumns.push([index, $(this).data('tabledit-field') || $(this).text().toLowerCase()]);
}
});

// Configura Tabledit
$table.Tabledit({
url: $table.data('tabledit-url'),
inputClass: 'form-control form-control-sm',
columns: {
identifier: [identifierColumn, 'id'],
editable: editableColumns
},
buttons: {
edit: {
class: 'btn btn-sm btn-primary',
html: '[i][/i]'
},
save: {
class: 'btn btn-sm btn-success',
html: '[i][/i]'
},
restore: {
class: 'btn btn-sm btn-warning',
html: '[i][/i]'
}
},
onDraw: function () {
// Disabilita input in base al TipoDato
$table.find('tr').each(function () {
var $row = $(this);
var tipoDato = parseInt($row.data('tipo-dato'));

// Se tipoDato è Valore (assumiamo sia 0)
if (tipoDato === 0) {
$row.find('td:eq(2)').find('input.tabledit-input').prop('disabled', true);
$row.find('td:eq(2)').find('.tabledit-span').addClass('text-muted');
}
// Se tipoDato è Quantità (assumiamo sia 1)
else if (tipoDato === 1) {
$row.find('td:eq(3)').find('input.tabledit-input').prop('disabled', true);
$row.find('td:eq(3)').find('.tabledit-span').addClass('text-muted');
}
});
},
onSuccess:  function (data, textStatus, jqXHR) {
console.log('Success:', data);
if (data.success) {
toastr.success('Modifiche salvate con successo');

var $row = $table.find('tr').has('td:contains("' + data.data.id + '")');

// Aggiorna i valori delle celle span (display originale)
$row.find('td:eq(2) span.tabledit-span').text(data.data.pezzi);
$row.find('td:eq(3) span.tabledit-span').text(data.data.kg);
$row.find('td:eq(5)').text(data.data.importoRiga);

// Aggiorna i valori degli input
$row.find('td:eq(2) input.tabledit-input').val(data.data.pezzi);
$row.find('td:eq(3) input.tabledit-input').val(data.data.kg);

// Nascondi gli input e mostra gli span
$row.find('.tabledit-input').hide();
$row.find('.tabledit-span').show();

// Riapplica la disabilitazione degli input
var tipoDato = parseInt($row.data('tipo-dato'));
if (tipoDato === 0) {
$row.find('td:eq(2)').find('input.tabledit-input').prop('disabled', true);
$row.find('td:eq(2)').find('.tabledit-span').addClass('text-muted');
} else if (tipoDato === 1) {
$row.find('td:eq(3)').find('input.tabledit-input').prop('disabled', true);
$row.find('td:eq(3)').find('.tabledit-span').addClass('text-muted');
}

// Reset dello stato dei pulsanti
$row.find('.tabledit-toolbar button').prop('disabled', false);
$row.find('.tabledit-toolbar').removeClass('tabledit-toolbar-editing');

// Evidenzia brevemente la riga aggiornata
$row.addClass('table-success');
setTimeout(function () {
$row.removeClass('table-success');
}, 1500);
} else {
toastr.error(data.message || 'Errore durante il salvataggio');
}
},
onFail: function (jqXHR, textStatus, errorThrown) {
console.error('Failed:', jqXHR.responseText);
toastr.error('Errore durante il salvataggio');
}
});
});
}

// Inizializza quando il documento è pronto
initAutoTabledit();

// Reinizializza quando una modale viene mostrata
$('.modal').on('shown.bs.modal', function () {
setTimeout(initAutoTabledit, 200);
});
});
но не работает. Оба столбца остаются доступными для редактирования.
Есть ли у кого-нибудь решение?

Подробнее здесь: https://stackoverflow.com/questions/793 ... n-conditio
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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