Pages

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

function initMap(did) { //// google map var locations = []; var markers = []; var myLatlng = { lat: 7.566372605265147, lng: 80.74644779929662 }; var map = new google.maps.Map(document.getElementById("map"), { zoom: 8, center: myLatlng, }); // add new for division wise map let urlMap = '/api/dashboard/getwarehousetbl'; if (did) { urlMap += `?companycode=${did}`; } fetch(urlMap) //fetch('/api/dashboard/getwarehousetbl') // old code .then(response => response.json()) .then(data => { let completedLocations = data.completed; let startedLocations = data.started; let pendingLocations = data.pending; if (Array.isArray(completedLocations)) { completedLocations.forEach(location => { locations.push([ ' C- ' + location.warehouseCode + '
' + 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

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(); }) }

Search This Blog