// disable QR search button on empty and page load const btnSerialS = document.getElementById('btnSerialS'); btnSerialS.disabled = true; function validateEmpty(){ const serialNumberD = document.getElementById("serialNum").value; if (serialNumberD.length > 5) { btnSerialS.disabled = false; } else { btnSerialS.disabled = true; } } /// function getWdata() { const hostName = window.location.host; const serialNumber = document.getElementById("serialNum").value; const url = `https://${hostName}/Api/get-check-warranty-activetion-by-serial-number?serialNumber=${serialNumber}`; fetch(url) .then(response => { if (!response.ok) { throw new Error(`No Information available. Please re-check the Serial Number again.`); } return response.json(); }) .then(data => { if (!data.data || data.data.length === 0) { alert("No data available, Please check the serial number"); // Reset the displayed values resetDisplayedValues(); } else { const firstData = data.data[0]; document.getElementById("serialNumber").textContent = firstData.serialNumber; document.getElementById("productName").textContent = firstData.productName; document.getElementById("productCode").textContent = firstData.productCode; document.getElementById("consumerName").textContent = firstData.consumerName; document.getElementById("consumerAddress").textContent = firstData.consumerAddress; document.getElementById("consumerContactNo").textContent = firstData.consumerNumber; document.getElementById("warrantyActivatedDate").textContent = firstData.warrantyActivatedDate; document.getElementById("warrantyExpiryDate").textContent = firstData.warrantyExpiryDate; document.getElementById("status").textContent = firstData.warrantyStatus; var myModal = new bootstrap.Modal(document.getElementById('warrantyModal'), { keyboard: false }); myModal.show(); } }) .catch(error => { alert(error.message); console.error(error); // Reset the displayed values resetDisplayedValues(); }); } function resetDisplayedValues() { document.getElementById("serialNumber").textContent = ""; document.getElementById("productName").textContent = ""; document.getElementById("productCode").textContent = ""; document.getElementById("consumerName").textContent = ""; document.getElementById("consumerAddress").textContent = ""; document.getElementById("consumerContactNo").textContent = ""; document.getElementById("warrantyActivatedDate").textContent = ""; document.getElementById("warrantyExpiryDate").textContent = ""; document.getElementById("status").textContent = ""; } function getNumdata() { //const hostName = window.location.hostname; const hostName = window.location.host; const phoneNum = document.getElementById("phoneNum").value; const url = `https://${hostName}/Api/get-consumer-active-warranty-serial-number-by-phone-number?phoneNumber=${phoneNum}`; //alert(phoneNum); //alert(url); fetch(url) .then(response => { if (!response.ok) { //throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`No Information available. Please re-check the Serial Number again.`); } return response.json(); }) .then(data => { if (!data) { document.getElementById("errorText").innerHTML = "<p>Please recheck the serial number.</p>" alert("No data available"); } else { //alert(JSON.stringify(data.data)); const deviceList = document.getElementById("deviceList"); deviceList.innerHTML = ""; const headertxtbym = document.getElementById("headertxtbym"); headertxtbym.innerHTML = ' <li class="list-group-item active" aria-current="true">Registered Devices</li>'; data.data.forEach(serialNumber => { const listitem = document.createElement("li"); listitem.classList.add("list-group-item"); listitem.setAttribute("data-seno", serialNumber); const link = document.createElement("a"); link.href = "#site"; link.classList.add("snoClick"); link.textContent = serialNumber; link.setAttribute("data-seno", serialNumber); listitem.appendChild(link); deviceList.appendChild(listitem); }); //////////////////////////////////////////////////////////////////////// //// pass SN from link auto to serial number form var listItems = document.querySelectorAll('.snoClick'); // Add a click event listener to each list item listItems.forEach(function(item) { item.addEventListener('click', function(e) { e.preventDefault(); // Get the value of the "data-seno" attribute var dataSeno = item.getAttribute('data-seno'); const dataSenoValue = this.getAttribute("data-seno"); const serialNumTextbox = document.getElementById("serialNum"); serialNumTextbox.value = dataSenoValue; btnSerialS.disabled = false; if (btnSerialS) { btnSerialS.click(); // Trigger click event on btnSerialS if it exists } }); }); } }) .catch(error => { alert(error.message); console.error(error); }); } // JavaScript code
Javascript Call API can Fetch Data - Get Method
Pass Data Attr Value from Link to BS popup go display data
<button title="View Label" type="button" class="btn btn-primary btn-sm m-1 openFrame" data-path="@item.ImagePath"> <i data-feather="image"></i> </button>
<script> // open label viwer var openFrame = document.querySelectorAll('.openFrame'); for(var i=0; i< openFrame.length; i++){ openFrame[i].addEventListener('click',function(){ var ImgPath = this.getAttribute('data-path'); //alert(ImgPath); var viewImgeFrame = document.getElementById('viewImgeFrame'); viewImgeFrame.src = ImgPath; viewImgeFrame.classList.add("img-fluid"); var lableViewer = new bootstrap.Modal(document.getElementById('lableViewer')); lableViewer.show(); }) } // open item log </script> }
Call API on click functions to update data
var roleUpdate = document.querySelectorAll('.roleUpdate');
for (var i = 0; i < roleUpdate.length; i++) {
roleUpdate[i].addEventListener('click', function () {
var permissionUserId = this.getAttribute('data-user-id');
var permissionCodeId = this.getAttribute('data-role-code');
const requestData = {
UserId: permissionUserId,
RoleId: permissionCodeId
};
//alert(JSON.stringify(requestData));
fetch(`${window.location.origin}/api/users/updaterole`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Error: ${response.status}`);
}
})
.then((data) => {
toastr.success('Update User Roles Success');
// alert(data.msg);
})
.catch((error) => {
// alert(error.message);
toastr.error('Update Failed');
});
});
}
// User Active Inactive status update
var userStatus = document.getElementById("userStatus");
userStatus.addEventListener('click', function () {
var puserStatusId = this.getAttribute('data-user-id');
alert(puserStatusId);
const requestData = {
UserId: puserStatusId,
};
//alert(JSON.stringify(requestData));
fetch(`${window.location.origin}/api/users/updaterole`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error(`Error: ${response.status}`);
}
})
.then((data) => {
toastr.success('Update User Status Success');
// alert(data.msg);
})
.catch((error) => {
// alert(error.message);
toastr.error('Update Failed');
});
});
HTML Data tables all options example
<table id="basic-datatable-Users" class="table table-striped dt-responsive nowrap w-100">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Role</th>
<th>HRIS No</th>
<th>Bar Code</th>
<th>Supervisor</th>
<th>User Skill</th>
<th>Is Active</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model.Users)
{
<tr>
<td>
@user.FullName
</td>
<td>@user.PhoneNumber</td>
<td>@user.Email</td>
<td>@user.RoleName</td>
<td>@user.HrisNo</td>
<td>@user.BarCode</td>
<td>@user.Supervisor</td>
<td>@user.UserSkill</td>
<td>
@if (user.IsActive == true)
{
<div class="form-check form-switch">
<input data-toggle="ajax-modal" type="checkbox" checked disabled class="form-check-input">
</div>
}
else
{
<div class="form-check form-switch">
<input data-toggle="ajax-modal" type="checkbox" disabled class="form-check-input">
</div>
}
</td>
<td>
<a href="/user/details?id=@user.Id" type="button" title="User Edit" class="btn btn-sm btn-soft-primary rounded-pill">
<i class="mdi mdi-account-edit-outline"></i>
</a>
<button type="button" title="Deactivate" class="btn btn-sm btn-soft-primary rounded-pill" data-bs-toggle="modal" data-id="@user.Id" onclick="OpenUserDeleteSubmit(this);">
<i class="mdi mdi-delete"></i>
</button>
</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Role</th>
<th>HRIS No</th>
<th>Bar Code</th>
<th>Supervisor</th>
<th>User Skill</th>
<th>Is Active</th>
<th>Action</th>
</tr>
</tfoot>
</table>
<!-- Datatables css -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.6.2/css/select.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" />
<style>
div.dataTables_wrapper {
width: 100%;
margin: 0 auto;
}
.dt-button.buttons-excel{
background: #727cf5;
color:#fff;
border:0;
}
thead input {
width: 100%;
border:1px solid #ededed;
}
</style>
@section Scripts {
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.6.2/js/dataTables.select.min.js"></script>
<script>
$(document).ready(function () {
$('#basic-datatable-Users thead tr')
.clone(true)
.addClass('filters')
.appendTo('#basic-datatable-Users thead');
///
///
$("#basic-datatable-Users").DataTable({
orderCellsTop: true,
dom: 'Bfrtip',
scrollX: true,
responsive : true,
buttons: [{
extend: 'excelHtml5',
exportOptions: {
columns: [1, 2, 3, 4, 5, 6, 7, 8, 9]
}
}
],
select: {
style: 'multi'
},
keys: !0,
language: {
paginate: {
previous: "<i class='mdi mdi-chevron-left'>",
next: "<i class='mdi mdi-chevron-right'>"
}
},
drawCallback: function () {
$(".dataTables_paginate > .pagination").addClass("pagination-rounded")
},
//clear autocomplete
initComplete: function () {
var api = this.api();
// Define the columns that require filters
var filterColumns = [1, 2, 3, 4];
// For each column
api.columns().eq(0).each(function (colIdx) {
var cell = $('.filters th').eq($(api.column(colIdx).header()).index());
if (filterColumns.includes(colIdx)) {
// Set the header cell to contain the input element
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$('input', cell)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})';
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
} else {
// Empty the header cell
$(cell).empty();
}
});
$(this.api().table().container()).find('input[type="search"]').parent().wrap('<form>').parent().attr('autocomplete', 'off').css('overflow', 'hidden').css('margin', 'auto');
}
});
});
/////
</script>
}
Jquery Data Tables Complete essential Example
<pre>
<table id="basic-datatable" class="display table-bordered nowrap table table-striped table-sm" style="font-size:12px;">
<thead>
<tr>
<th>Action</th>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Designation</th>
<th>Start Day/Time</th>
<th>Meter Reading</th>
<th>Start Remarks</th>
<th>End Day/Time</th>
<th>Meter Reading</th>
<th>End Remarks</th>
<th>Attachments</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr class="align-middle">
<td class="text-nowrap text-end">
<a class="btn btn-link p-0" href="~/DayInOut/ShowMapRoute?id=@item.Session" data-bs-toggle="tooltip" data-bs-placement="top" title="View Route" onclick="GetRouteById(@item.Session)">
<i class="mdi mdi-archive-edit"></i>
</a>
</td>
<td class="text-nowrap fw-bold">
<span title="@item.Client" class="d-inline-block text-truncate" style="max-width: 100px;"> E10001</span>
</td>
<td class="text-nowrap">
<span title="@item.Client" class="d-inline-block text-truncate" style="max-width: 100px;"> Tharaka Jayampathi </span>
</td>
<td class="text-nowrap">DivisionalCodinator</td>
<td class="text-nowrap fw-bold">
@if (item.DayStart.HasValue)
{
@item.DayStart.Value.ToString("M/d/yyyy")
<br>
@item.DayStart.Value.ToString("h:mm:ss tt")
}
else
{
<p>???</p>
}
<td class="text-nowrap">@item.StartMileage </td>
<td class="text-nowrap">@item.DayStartRemark </td>
<td class="text-nowrap fw-bold">
@if (item.DayEnd.HasValue)
{
@item.DayEnd.Value.ToString("M/d/yyyy")
<br>
@item.DayEnd.Value.ToString("h:mm:ss tt")
}
else
{
<p>???</p>
}
</td>
<td class="text-nowrap">@item.EndMileage </td>
<td class="text-nowrap">@item.DayEndRemark </td>
<td class="text-nowrap">
@if (item.DayStartAttachment != "" && item.DayStartAttachment != null)
{
<a title="Start" style=" border: 1px solid #dedede; margin-right: 5px;" class="btn px-2 btn-success btn btn-sm" target="_blank" href="@item.DayStartAttachment" download>
<i class="far fa-file-image"></i>
</a>
}
@if (item.DayEndAttachment != "" && item.DayEndAttachment != null)
{
<a title="End" style=" border: 1px solid #dedede; margin-right: 5px;" class="btn px-2 btn-danger btn btn-sm" target="_blank" href="@item.DayEndAttachment" download>
<i class="far fa-file-image"></i>
</a>
}
</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<th>Action</th>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Designation</th>
<th>Start Day/Time</th>
<th>Meter Reading</th>
<th>Start Remarks</th>
<th>End Day/Time</th>
<th>Meter Reading</th>
<th>End Remarks</th>
<th>Attachments</th>
</tr>
</tfoot>
</table>
@section Styles {
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.6.2/css/select.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" />
<style>
div.dataTables_wrapper {
width: 100%;
margin: 0 auto;
}
thead input {
width: 100%;
}
</style>
}
@section Scripts{
<script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.6.2/js/dataTables.select.min.js"></script>
<script>
$(document).ready(function () {
// Setup - add a text input to specific footer cells
$('#basic-datatable thead tr')
.clone(true)
.addClass('filters')
.appendTo('#basic-datatable thead');
$("#basic-datatable").DataTable({
orderCellsTop: true,
dom: 'Bfrtip',
scrollX: true,
buttons: [{
extend: 'excelHtml5',
exportOptions: {
columns: [1, 2, 3, 4,5,6,7,8,9]
}
}
],
select: {
style: 'multi'
},
initComplete: function () {
var api = this.api();
// Define the columns that require filters
var filterColumns = [1, 2, 3, 4, 5, 6, 7, 8];
// For each column
api.columns().eq(0).each(function (colIdx) {
var cell = $('.filters th').eq($(api.column(colIdx).header()).index());
if (filterColumns.includes(colIdx)) {
// Set the header cell to contain the input element
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$('input', cell)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})';
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
} else {
// Empty the header cell
$(cell).empty();
}
});
},
});
});
</script>
</pre>