1
I’m a beginner with Javascript and I’m having a problem when the Datatable of my Index is loaded.
If I open a section, on my Index, and put the JS code inside it, everything works perfectly.
@{
ViewData["Title"] = "Gerenciar Situações de Pessoa";
}
<div class="panel animsition">
<div class="page-header">
<h1 class="page-title">@ViewData["Title"]</h1>
<ol class="breadcrumb">
<li><a asp-action="Index" asp-controller="Home">Home</a></li>
<li class="active">situacoes-gerenciamento/listar-todos</li>
</ol>
<div class="page-header-actions">
<div class="btn-group btn-group-sm"
role="group">
<a id="btnNovo" asp-action="Create" data-modal="" class="btn btn-outline btn-default new" data-toggle="tooltip"
data-original-title="Cadastrar Novo" data-container="body">
<span title="Cadastrar Novo" class="icon wb-plus"></span> Cadastrar Novo
</a>
<button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
data-original-title="Configurações" data-container="body">
<i class="icon wb-settings" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
data-original-title="Exportar" data-container="body">
<i class="icon wb-upload" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
data-original-title="Importar" data-container="body">
<i class="icon wb-download" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
data-original-title="Imprimir" data-container="body">
<i class="icon wb-print" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
data-original-title="Pesquisa Avançada" data-container="body">
<i class="icon wb-search" aria-hidden="true"></i>
<span class="hidden-xs">Pesquisa Avançada</span>
</button>
</div>
</div>
</div>
<div class="page-content">
<table id="pessoaSituacaoTable" class="table table-striped table-bordered center-header " cellspacing="0" width="100%">
<thead>
<tr>
<th>
Id
</th>
<th>
Descrição
</th>
<th>
Tipo de Pessoa
</th>
<th>
Ações
</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal fade modal-primary" id="modalPessoaSituacao" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog" style="width: 45%; height: 500px;">
<div class="modal-content">
<div id="contentModal"></div>
</div>
</div>
</div>
@section scripts {
<script type="text/javascript">
$(function () {
$('.dataTables_filter input').attr('placeholder', 'Search...').hide();
var table = $("#pessoaSituacaoTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
//"dom": '<"top"i>rt<"bottom"lp><"clear">',
"ajax": {
"url": '@Url.Action("getPessoaSituacao", "PessoaSituacao")',
"type": "POST",
"datatype": "json"
},
"columnDefs": [
{ className: "align-center", "targets": [3] },
{ className: "align-right", "targets": [0] }
],
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true },
{ "data": "descricao", "name": "Descricao", "autoWidth": true },
{ "data": "pessoaTipoDescricao", "name": "PessoaTipo", "autoWidth": true },
{
"data": null, "name": "Action", "defaultContent": '<a title="Editar" asp-action="Edit" data-modal="" data-id="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"><span class="icon-2x wb-edit"></span></a> |' +
'<a title="Detalhes" asp-action="Details" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row"><span class="icon-2x wb-search"></span></a> |' +
'<a title="Excluir" asp-action="Delete" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row"><span class="icon-2x wb-trash"></span></a> |' +
'<a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico"><span class="icon-2x wb-time"></span></a>', "autoWidth": true
}
],
"language": {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar",
"searchPlaceholder": "Digite algo...",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
}
});
$('.search-input').on('keyup change', function () {
var index = $(this).attr('data-column'),
val = $(this).val();
table.columns(index).search(val.trim()).draw();
});
});
}
PROBLEM: If I transfer the code to a JS script and refer it to my Index, it does not work and keeps displaying the error message I quoted above. What am I doing wrong?
//Meu Arquivo PessoaSituacao.js
$(document).ready(function () {
$.ajaxSetup({ cache: false });
// busca os elementos do atributo data-modal e o vincula ao evento click
$('a[data-modal]').on('click', function (e) {
// Abre a janela modal com o formulário solicitado
openmodal(this.href);
return false;
});
$('#modalPessoaSituacao').on('hidden.bs.modal', function () {
$('#contentModal').html('');
});
$(function () {
$('.dataTables_filter input').attr('placeholder', 'Search...').hide();
var table = $("#pessoaSituacaoTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
//"dom": '<"top"i>rt<"bottom"lp><"clear">',
"ajax": {
"url": '@Url.Action("getPessoaSituacao", "PessoaSituacao")',
"type": "POST",
"datatype": "json"
},
"columnDefs": [
{ className: "align-center", "targets": [3] },
{ className: "align-right", "targets": [0] }
],
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true },
{ "data": "descricao", "name": "Descricao", "autoWidth": true },
{ "data": "pessoaTipoDescricao", "name": "PessoaTipo", "autoWidth": true },
{
"data": null, "name": "Action", "defaultContent": '<a title="Editar" asp-action="Edit" data-modal="" data-id="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"><span class="icon-2x wb-edit"></span></a> |' +
'<a title="Detalhes" asp-action="Details" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row"><span class="icon-2x wb-search"></span></a> |' +
'<a title="Excluir" asp-action="Delete" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row"><span class="icon-2x wb-trash"></span></a> |' +
'<a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico"><span class="icon-2x wb-time"></span></a>', "autoWidth": true
}
],
"language": {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar",
"searchPlaceholder": "Digite algo...",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
}
});
$('.search-input').on('keyup change', function () {
var index = $(this).attr('data-column'),
val = $(this).val();
table.columns(index).search(val.trim()).draw();
});
});
});
function openmodal(url) {
// Faz uma requisição Get e carrega o formulário na janela modal
$('#contentModal').load(url, function () {
$('#modalPessoaSituacao').modal({
keyboard: true
}, 'show');
//Enviar o foco para campo Descrição
$('#modalPessoaSituacao').on('shown.bs.modal', function(event) {
$("#txtDescricao").focus();
});
// Vincula o evento submit
bindForm(this);
});
}
function bindForm(dialog) {
// Vincula o formulário na janela modalcom o evento submit
$('form', dialog).submit(function () {
if ($(this).valid()) {
// Realiza uma querisição ajax
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// Se a requisição for satisfatória, a página atual é recarregada
if (result.success) {
window.location = window.location;
window.location.reload(); //Ajuda na exclusao, atualizando o grid
} else {
$('#contentModal').html(result);
bindForm();
}
}
});
return false;
} else {
return false;
}
});
}
Tries to take its function from within $(Document). ready() and puts it as an independent function.
– Maycon F. Castro
Hello Maycon! I took out take inside the block that you suggested, but continues the same error... I do not know very well of Javascript... I find it strange that this function without a name... gives the impression that it performs without being called.... :(
– Master JR