import { useState } from "react"; function Post(){ const [inval, setInVal] = useState(''); function changeTextHandler(e){ setInVal(e.target.value); } return ( <> <form> <textarea onChange={changeTextHandler}/> <div>{inval}</div> </form> </> ) }; export default Post;
Simple React Use State Example
Max length input validation inline with javascript
<input type="text" class="form-control" id="txtProjectCreateProjectCode"
placeholder="Project Code" required oninput="if (this.value.length > 50) this.value = this.value.slice(0, 50);" name="CreateProject.Code" value="">Bootstrap 5 Logout confirmation for .net core
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Logout Confirmation</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure you want to sign out? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <form id="logoutForm" asp-action="logoff" asp-controller="Auth" class="navbar-right"> <a class="btn btn-primary" @* onclick="return alert('Are you sure do you want to sign out?')" *@ href="javascript:document.getElementById('logoutForm').submit()"><i class="mdi mdi-logout me-1"></i><span>Logout</span></a> </form> </div> </div> </div> </div>
<a href="javascript:void(0);" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#exampleModal"> <i class="mdi mdi-logout me-1"></i> Logout </a>
OTP Countdown JavaScript Version 2 - Initial Page load countdown
<button id="resendOtp" class="btn mt-0 mb-3 d-block w-100" onclick="resendOtp()" type="button" style="border:0px solid #1f3d88; background:transparent; color:#1f3d88;"> <i class="fa-solid fa-rotate-right"></i> Resend OTP </button> <div id="countdown" style="display: block; text-align: center; font-size: 12px; color: #fdb827;"> Resend OTP in <span id="timer">120</span> seconds </div> <script> function startCountdown() { const resendButtonInit = document.getElementById("resendOtp"); resendButtonInit.disabled = true; let seconds = 120; // Function to update the countdown timer function updateTimer() { const timer = document.getElementById("timer"); timer.textContent = seconds; seconds--; if (seconds < 0) { // Hide the countdown when the timer reaches 0 const countdownDiv = document.getElementById("countdown"); countdownDiv.style.display = "none"; resendButtonInit.disabled = false; } else { // Continue updating the timer setTimeout(updateTimer, 1000); } } // Start the countdown updateTimer(); } // Call startCountdown function when the page loads window.onload = startCountdown; var resendOtpBtn = document.getElementById("resendOtp"); resendOtpBtn.addEventListener('click',function(){ resendOtp(); }); function resendOtp() { // Get the value of the textPhoneNumber input field const phoneNumber = document.getElementById("textPhoneNumber").value; // Disable the "Resend OTP" button const resendButton = document.getElementById("resendOtp"); resendButton.disabled = true; // Show the countdown timer const countdownDiv = document.getElementById("countdown"); countdownDiv.style.display = "block"; let seconds = 120; // Function to update the countdown timer function updateTimer() { const timer = document.getElementById("timer"); timer.textContent = seconds; seconds--; if (seconds < 0) { // Re-enable the button and hide the countdown when the timer reaches 0 resendButton.disabled = false; countdownDiv.style.display = "none"; } else { // Continue updating the timer setTimeout(updateTimer, 1000); } } // Start the countdown updateTimer(); // Create a JSON object with the MobileNo property const data = { MobileNo: phoneNumber }; // Send a POST request to the API endpoint fetch("https://localhost:7146/api/security/resend-otp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }) .then(response => { if (response.ok) { // Handle success //alert("OTP resend request successful"); } else { // Handle errors alert("OTP resend request failed"); } }) .catch(error => { console.error("An error occurred:", error); }); } </script>
OTP Countdown Script Javascript
<button id="resendOtp" class="btn mt-0 mb-3 d-block w-100" onclick="resendOtp()" type="button" style="border: 0px solid #1f3d88; background: transparent; color: #1f3d88;">Resend OTP</button> <input class="form-control valid" id="textPhoneNumber" readonly="" type="text" data-val="true" data-val-regex="Not a valid phone number." data-val-regex-pattern="^(?:7|0)[0-9]{9,9}$" data-val-required="Phone number is Required." name="PhoneNumber" value="0717194022" aria-describedby="textPhoneNumber-error" aria-invalid="false"> <div id="countdown" style="display: block;">Resend OTP in <span id="timer">120</span> seconds</div> <script> function startCountdown() { let seconds = 120; // Function to update the countdown timer function updateTimer() { const timer = document.getElementById("timer"); timer.textContent = seconds; seconds--; if (seconds < 0) { // Hide the countdown when the timer reaches 0 const countdownDiv = document.getElementById("countdown"); countdownDiv.style.display = "none"; } else { // Continue updating the timer setTimeout(updateTimer, 1000); } } // Start the countdown updateTimer(); } // Call startCountdown function when the page loads window.onload = startCountdown; function resendOtp() { // Get the value of the textPhoneNumber input field const phoneNumber = document.getElementById("textPhoneNumber").value; // Disable the "Resend OTP" button const resendButton = document.getElementById("resendOtp"); resendButton.disabled = true; // Show the countdown timer const countdownDiv = document.getElementById("countdown"); countdownDiv.style.display = "block"; let seconds = 120; // Function to update the countdown timer function updateTimer() { const timer = document.getElementById("timer"); timer.textContent = seconds; seconds--; if (seconds < 0) { // Re-enable the button and hide the countdown when the timer reaches 0 resendButton.disabled = false; countdownDiv.style.display = "none"; } else { // Continue updating the timer setTimeout(updateTimer, 1000); } } // Start the countdown updateTimer(); // Create a JSON object with the MobileNo property const data = { MobileNo: phoneNumber }; // Send a POST request to the API endpoint fetch("https://localhost:7146/api/security/resend-otp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }) .then(response => { if (response.ok) { // Handle success console.log("OTP resend request successful"); // You can add further code here for a successful response } else { // Handle errors console.error("OTP resend request failed"); // You can add error handling code here } }) .catch(error => { console.error("An error occurred:", error); // Handle network errors here }); } </script>
Boostrap 5 Common code to place on layout page, then any boostrap modal on close, form data inside the modal will be cleared
<pre> <script> document.addEventListener('hidden.bs.modal', function (e) { var modal = e.target; // The modal that triggered the event // Check if the modal contains a form var form = modal.querySelector('form'); if (form) { form.reset(); // Reset the form if a form is found } }); </script> </pre>
Sample Google Maps Dashboard Application for Stock Count
' + location.warehouseName + '
' + 'View Location Details', location.latitude, location.longitude, location.status ]); }); } if (Array.isArray(startedLocations)) { startedLocations.forEach(location => { locations.push([ '' + location.warehouseCode + '
' + location.warehouseName + '
' + 'View Location Details', location.latitude, location.longitude, location.status ]); }); } if (Array.isArray(pendingLocations)) { pendingLocations.forEach(location => { locations.push([ '' + location.warehouseCode + '
' + location.warehouseName + '
' + 'View Location Details', location.latitude, location.longitude, location.status ]); }); } var infowindow = new google.maps.InfoWindow({}); var marker, count; var bounds = new google.maps.LatLngBounds(); //// hide map if all locations are 0 let zeroLocations = 0; for (count = 0; count < locations.length; count++) { if (locations[count][1] == 0 && locations[count][2] == 0) { zeroLocations++; } } let tdcolw = document.getElementById("tdcolw"); if (zeroLocations === locations.length) { document.getElementById("mapcol").style.display = "none"; tdcolw.classList.remove("col-lg-12"); tdcolw.classList.add("col-lg-9"); } else { document.getElementById("mapcol").style.display = "block"; tdcolw.classList.remove("col-lg-9"); tdcolw.classList.add("col-lg-12"); } //// for (count = 0; count < locations.length; count++) { let iconUrl; if (locations[count][3] === 'COMPLETED') { iconUrl = 'images/completedm.png'; } else if (locations[count][3] === 'PENDING') { iconUrl = 'images/plannedm.png'; } else { iconUrl = 'images/active.gif'; } if (locations[count][1] !== 0 && locations[count][2] !== 0) { // avoid empty or 0 lat long locations marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[count][1], locations[count][2]), map: map, title: locations[count][0], icon: iconUrl }); google.maps.event.addListener(marker, 'click', (function (marker, count) { return function () { infowindow.setContent(locations[count][0]); infowindow.open(map, marker); } })(marker, count)); markers.push(marker); bounds.extend(marker.getPosition()); } } map.fitBounds(bounds); }) .catch(error => console.error(error)); } window.initMap = initMap; function loadOffcanvas(event) { event.preventDefault(); var dataId = event.target.getAttribute("data-id"); var dataName = event.target.getAttribute("data-name"); var dataStatus = event.target.getAttribute("data-status"); var myOffcanvas = document.getElementById('offcanvasBottom'); var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas); bsOffcanvas.show(); var whCodedisplayHeading = document.getElementById("offcanvasBottomLabel"); whCodedisplayHeading.innerHTML = dataId; var whCodedisplayHeadingName = document.getElementById("whNamedisplay"); whCodedisplayHeadingName.innerHTML = dataName; var whStatusD = document.getElementById("statusLocation"); whStatusD.innerHTML = dataStatus; eChartDisplay(dataId); getConsignmentData(dataId); } //// get data about warehouse from consignment api function getConsignmentData(dataId) { fetch('/api/dashboard/getconsignmentwarehouse?warehouseCode=' + dataId) .then(response => response.json()) .then(data => { var isConsignment = data.nonConsignmentWarehouse.isConsignemnt; var nonConsignmentUsers = data.nonConsignmentUserViewModels; var consignmentUsers = data.consignmentUserViewModels; var nonConsignmentUsersList = ""; var consignmentUsersList = ""; if (!isConsignment) { nonConsignmentUsersList += "Non-consignment Location
User List:
"; nonConsignmentUsers.forEach(user => { nonConsignmentUsersList += `- ${user.fullName} (${user.roleName})
`; }); document.getElementById('location-data').innerHTML = nonConsignmentUsersList; } if (consignmentUsers.length > 0) { consignmentUsersList += "Consignment Location
User List:
"; consignmentUsers.forEach(user => { consignmentUsersList += `- ${user.fullName} (${user.roleName})
`; }); document.getElementById('location-data').innerHTML = consignmentUsersList; } //console.log(nonConsignmentUsersList); //console.log(consignmentUsersList); }) .catch(error => console.error(error)); } //// //// fill data in tables function AllLocationsDisplayTable(did) { //fetch("/api/dashboard/getwarehousetbl") let urlAllT = '/api/dashboard/getwarehousetbl'; if (did) { urlAllT += `?companycode=${did}`; } var completedLocations = []; var startedLocations = []; var pendingLocations = []; fetch(urlAllT) .then(response => response.json()) .then(data => { console.log(data); completedLocations = data.completed; var tableBodycompleted = document.querySelector("#completedTable tbody"); tableBodycompleted.innerHTML = ""; for (var i = 0; i < completedLocations.length; i++) { var tr = document.createElement("tr"); var td1 = document.createElement("td"); var td2 = document.createElement("td"); var td5 = document.createElement("td"); var td6 = document.createElement("td"); td1.innerHTML = completedLocations[i].warehouseCode; td2.innerHTML = completedLocations[i].warehouseName; td5.innerHTML = completedLocations[i].status; td6.innerHTML = 'View Location Details'; tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td5); tr.appendChild(td6); tableBodycompleted.appendChild(tr); } $('#completedTable').DataTable(); /////////// started table startedLocations = data.started; var tableBodystarted = document.querySelector("#startedTable tbody"); tableBodystarted.innerHTML = ""; for (var i = 0; i < startedLocations.length; i++) { var tr = document.createElement("tr"); var td1 = document.createElement("td"); var td2 = document.createElement("td"); var td5 = document.createElement("td"); var td6 = document.createElement("td"); td1.innerHTML = startedLocations[i].warehouseCode; td2.innerHTML = startedLocations[i].warehouseName; td5.innerHTML = startedLocations[i].status; td6.innerHTML = 'View Location Details'; tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td5); tr.appendChild(td6); tableBodystarted.appendChild(tr); } $('#startedTable').DataTable(); /////////// pending table pendingLocations = data.pending; var tableBodypending = document.querySelector("#pendingTable tbody"); tableBodypending.innerHTML = ""; for (var i = 0; i < pendingLocations.length; i++) { var tr = document.createElement("tr"); var td1 = document.createElement("td"); var td2 = document.createElement("td"); var td5 = document.createElement("td"); var td6 = document.createElement("td"); td1.innerHTML = pendingLocations[i].warehouseCode; td2.innerHTML = pendingLocations[i].warehouseName; td5.innerHTML = pendingLocations[i].status; td6.innerHTML = 'View Location Details'; tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td5); tr.appendChild(td6); tableBodypending.appendChild(tr); } $('#pendingTable').DataTable(); }); } setInterval(function () { var selectD = document.querySelector("#companySelect"); var selectedValue = selectD.value; AllLocationsDisplayTable(selectedValue); }, 5000); //// echarts function eChartDisplay(dataId) { fetch('/api/dashboard/getvariancesbywarehouse/?warehouseCode=' + encodeURIComponent(dataId)) .then(response => response.json()) .then(({ varaince, nonVaraince, extras }) => { document.getElementById('varianceD').innerHTML = varaince; document.getElementById('novarianceD').innerHTML = nonVaraince; document.getElementById('extraD').innerHTML = extras; var dom = document.getElementById('chart-container'); var myChart = echarts.init(dom, null, { renderer: 'canvas', useDirtyRect: false }); var app = {}; var option; var colorPalette = ['#FF5A49', '#2BD59C', '#E89B26']; option = { tooltip: { trigger: 'item' }, legend: { top: '5%', left: 'center' }, series: [ { name: 'Access From', type: 'pie', radius: ['40%', '70%'], avoidLabelOverlap: false, color: colorPalette, itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: 40, fontWeight: 'bold' } }, labelLine: { show: false }, data: [ { value: varaince, name: 'Variance' }, { value: nonVaraince, name: 'No Variance' }, { value: extras, name: 'Extra Items' } ] } ] }; if (option && typeof option === 'object') { myChart.setOption(option); } window.addEventListener('resize', myChart.resize); }) .catch(error => console.error(error)); } //// Display current date time setInterval(function () { // Get the textbox element var textbox = document.getElementById("textDate"); // Get the current date and time var currentDate = new Date(); // Format the date as a string var dateString = currentDate.toLocaleString(); // Set the textbox value to the formatted date textbox.value = dateString; }, 1000); // 1000 milliseconds = 1 second //// Day summery progress bar setInterval(function () { // Get the span elements var sspan1 = document.getElementById("completedLocationsd"); var sspan2 = document.getElementById("countingLocationsd"); var sspan3 = document.getElementById("pLocationsd"); // Get the values inside the spans var cvalue1 = parseFloat(sspan1.innerHTML.replace(/,/g, '')); var cvalue2 = parseFloat(sspan2.innerHTML.replace(/,/g, '')); var cvalue3 = parseFloat(sspan3.innerHTML.replace(/,/g, '')); //alert(cvalue1); // Calculate the total value var total = cvalue1 + cvalue2 + cvalue3; // Calculate the percentages var cpercent1 = (cvalue1 / total) * 100; var cpercent2 = (cvalue2 / total) * 100; var cpercent3 = (cvalue3 / total) * 100; // Get the div elements var pdiv1 = document.getElementById("progress1"); var pdiv2 = document.getElementById("progress2"); var pdiv3 = document.getElementById("progress3"); // Set the CSS width of the divs based on the percentages pdiv1.style.width = cpercent1 + "%"; pdiv2.style.width = cpercent2 + "%"; pdiv3.style.width = cpercent3 + "%"; }, 5000); // 5000 milliseconds = 5 seconds //// warehouse count var allLocationsd = document.getElementById("allLocationsd"); var completedLocationsd = document.getElementById("completedLocationsd"); var countingLocationsd = document.getElementById("countingLocationsd"); var pLocationsd = document.getElementById("pLocationsd"); function updateData(did) { // change url of api if have to pass or passing another value let urlAll = '/api/dashboard/getwarehousecount'; if (did) { urlAll += `?companycode=${did}`; } fetch(urlAll) .then(response => response.json()) .then(data => { allLocationsd.innerHTML = JSON.stringify(data); }) .catch(error => console.error(error)); //////////// completed warehosue all or division wise | did = division id let urlCompleted = '/api/dashboard/getwarehousecompleted'; if (did) { urlCompleted += `?companycode=${did}`; } fetch(urlCompleted) .then(response => response.json()) .then(data => { completedLocationsd.innerHTML = JSON.stringify(data); }) .catch(error => console.error(error)); //////////// let urlStarted = '/api/dashboard/getwarehousetarted'; if (did) { urlStarted += `?companycode=${did}`; } fetch(urlStarted) .then(response => response.json()) .then(data => { countingLocationsd.innerHTML = JSON.stringify(data); }) .catch(error => console.error(error)); //////////// let urlPending = '/api/dashboard/getwarehousepending'; if (did) { urlPending += `?companycode=${did}`; } fetch(urlPending) .then(response => response.json()) .then(data => { pLocationsd.innerHTML = JSON.stringify(data); }) .catch(error => console.error(error)); //////////// } setInterval(function () { var selectD = document.querySelector("#companySelect"); var selectedValue = selectD.value; updateData(selectedValue); }, 5000); // 5000 milliseconds = 5 second //// bind values to divisions/ company drop down function bindCompanyData() { fetch("/api/dashboard/getdivisions") .then(response => response.json()) .then(data => { var select = document.querySelector("#companySelect"); for (var i = 0; i < data.length; i++) { var option = document.createElement("option"); option.text = data[i].companyDescription; option.value = data[i].companyCode; select.appendChild(option); } }); } bindCompanyData(); //// division selectbox change select box var selectD = document.querySelector("#companySelect"); selectD.addEventListener("change", function () { var selectedValue = selectD.value; if (!selectedValue) { ; location.reload(); return; } else { // clear tables var tableBodycompleted = document.querySelector("#completedTable tbody"); tableBodycompleted.innerHTML = ""; var tableBodystarted = document.querySelector("#startedTable tbody"); tableBodystarted.innerHTML = ""; var tableBodypending = document.querySelector("#pendingTable tbody"); tableBodypending.innerHTML = ""; if ($('#startedTable').length) { $('#startedTable').DataTable().destroy(); } if ($('#pendingTable').length) { $('#pendingTable').DataTable().destroy(); } if ($('#completedTable').length) { $('#completedTable').DataTable().destroy(); } //call fucntions updateData(selectedValue); initMap(selectedValue); AllLocationsDisplayTable(selectedValue); } }); feather.replace();
Call api Data and show in a Bootstrap table : Javascript
var itmLogOpen = document.querySelectorAll('.itmLogOpen'); for(var x=0; x<itmLogOpen.length; x++){ itmLogOpen[x].addEventListener('click',function(){ var Serialitmno = this.getAttribute('data-itmno'); displayLblog(Serialitmno); }) } function displayLblog(Serialitmno) { const hostname = window.location.host; const url = `https://${hostname}/api/log/print/details/label?division=11&serialNo=${Serialitmno}`; 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 { //alert(JSON.stringify(data)); const datalogTable = document.querySelector("#datalogTable tbody") datalogTable.innerHTML = ""; data.data.forEach(item=>{ const trow = document.createElement("tr"); trow.innerHTML=` <td>${item.printedBy}</td> <td>${item.formattedDate}</td> `; datalogTable.appendChild(trow); }); var logViewer = new bootstrap.Modal(document.getElementById('logViewer')); logViewer.show(); } }) .catch(error => { alert(error.message); console.error(error); // Reset the displayed values // resetDisplayedValues(); }); }
Get data from a Button and display on popup
Javascript Call API can Fetch Data - Get Method
// 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
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');
});
});