How to access Axios without using react?

I’m having a difficult time understanding how to use Axios instead of Fetch. For some reason, my code works well with Fetch but not with Axios. Below is my code. Note: You will need your personal API keys to run the code.

<!DOCTYPE html>
<html>

    <!-- add your Google Maps API to line 4 after the =  -->
<head>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.1/axios.min.js"></script>

    <script src="http://maps.google.com/maps/api/js?key=ADDYOURKEYHERE"></script>
    <style>
        body { margin: 0; padding: 0; }
        /* #map { position: absolute; top: 0; bottom: 0; width: 100%; } */
        /* .map-overlay {
        position: absolute;
        left: 0;
        padding: 10px;
      } */
      </style>
</head>
<body>
    <div id="map" style="width:1024px; height:768px"></div>
    <!-- <div class="map-overlay top">
        <button onclick="addMarker()">SHOW ROUTE FROM MIT TO HARVARD - BUS ONE</button>
       </div>  -->
    <script>

        var map;
        var markers = [];

        // load map
        function init(){
            var myOptions = {
                zoom      : 14,
                center    : { lat:42.353350,lng:-71.091525},
                mapTypeId : google.maps.MapTypeId.ROADMAP
            };
            var element = document.getElementById('map');
            map = new google.maps.Map(element, myOptions);
            addMarkers();
        }

        init();
        //
        // Add bus markers to map
async function addMarkers(){
    // get bus data
    var locations = await getBusLocations();

    // loop through data, add bus markers
    locations.forEach(function(bus){
        var marker = getMarker(bus.id);     
        if (marker){
            moveMarker(marker,bus);
        }
        else{
            addMarker(bus);         
        }
    });

    // timer
    console.log(new Date());
    setTimeout(addMarkers,15000);
}

// Request bus data from MBTA
async function getBusLocations(){
    var url = 'https://api-v3.mbta.com/vehicles?api_key=ADDYOURKEYHERE&filter[route]=1&include=trip';   
    var response = await fetch(url);
    var json     = await response.json();
    return json.data;
}

function addMarker(bus){
    var icon = getIcon(bus);
    var marker = new google.maps.Marker({
        position: {
            lat: bus.attributes.latitude, 
            lng: bus.attributes.longitude
        },
        map: map,
        icon: icon,
        id: bus.id
    });
    markers.push(marker);
}

function getIcon(bus){
    // select icon based on bus direction
    if (bus.attributes.direction_id === 0) {
        return 'red.png';
    }
    return 'blue.png';  
}

function moveMarker(marker,bus) {
    // change icon if bus has changed direction
    var icon = getIcon(bus);
    marker.setIcon(icon);

    // move icon to new lat/lon
    marker.setPosition( {
        lat: bus.attributes.latitude, 
        lng: bus.attributes.longitude
    });
}

function getMarker(id){
    var marker = markers.find(function(item){
        return item.id === id;
    });
    return marker;
}



</script>
</body>
</html>

So, the code works well with Fetch; however, when I used Axios (using the Axios library), it doesn’t work. (See code below)

<!DOCTYPE html>
<html>

    <!-- add your Google Maps API to line 4 after the =  -->
<head>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.1/axios.min.js"></script>

    <script src="http://maps.google.com/maps/api/js?key=ADDYOURKEYHERE"></script>
    <style>
        body { margin: 0; padding: 0; }
        /* #map { position: absolute; top: 0; bottom: 0; width: 100%; } */
        /* .map-overlay {
        position: absolute;
        left: 0;
        padding: 10px;
      } */
      </style>
</head>
<body>
    <div id="map" style="width:1024px; height:768px"></div>
    <!-- <div class="map-overlay top">
        <button onclick="addMarker()">SHOW ROUTE FROM MIT TO HARVARD - BUS ONE</button>
       </div>  -->
    <script>

        var map;
        var markers = [];

        // load map
        function init(){
            var myOptions = {
                zoom      : 14,
                center    : { lat:42.353350,lng:-71.091525},
                mapTypeId : google.maps.MapTypeId.ROADMAP
            };
            var element = document.getElementById('map');
            map = new google.maps.Map(element, myOptions);
            addMarkers();
        }

        init();
        //
        // Add bus markers to map
async function addMarkers(){
    // get bus data
    var locations = await getBusLocations();

    // loop through data, add bus markers
    locations.forEach(function(bus){
        var marker = getMarker(bus.id);     
        if (marker){
            moveMarker(marker,bus);
        }
        else{
            addMarker(bus);         
        }
    });

    // timer
    console.log(new Date());
    setTimeout(addMarkers,15000);
}


//Request bus data from MBTA with axios instead fecth
async function getBusLocations(){
    var url = 'https://api-v3.mbta.com/vehicles?api_key=ADDYOURKEYHERE&filter[route]=1&include=trip';   
    var response = await axios(url);
    return await response.data;
}

function addMarker(bus){
    var icon = getIcon(bus);
    var marker = new google.maps.Marker({
        position: {
            lat: bus.attributes.latitude, 
            lng: bus.attributes.longitude
        },
        map: map,
        icon: icon,
        id: bus.id
    });
    markers.push(marker);
}

function getIcon(bus){
    // select icon based on bus direction
    if (bus.attributes.direction_id === 0) {
        return 'red.png';
    }
    return 'blue.png';  
}

function moveMarker(marker,bus) {
    // change icon if bus has changed direction
    var icon = getIcon(bus);
    marker.setIcon(icon);

    // move icon to new lat/lon
    marker.setPosition( {
        lat: bus.attributes.latitude, 
        lng: bus.attributes.longitude
    });
}

function getMarker(id){
    var marker = markers.find(function(item){
        return item.id === id;
    });
    return marker;
}



</script>
</body>
</html>

I tried to integrate Axios with the React app, but for some reason, it didn’t work. However, I’m wondering if there’s a way to use Axios without relying on React or npm. Additionally, I’ve already downloaded the Axios library before my code, but it doesn’t seem to have helped.

Search function only works on the first page and not on other pagination pages

The search box that I have added to my table is only working on the first page and not on the other pagination pages. I want it to show the search result from the entire table. And I also want to show the current page row count before the total page row count. You can see it at the bottom of the page. It will be really helpful if the expert helps me out with this.

    <!-- Table Search Script Starts -->

        function myFunction() {
            var input, filter, table, tr, td, i, txtValue, pagination;
            input = document.getElementById("myInput");
            filter = input.value.toLowerCase();
            table = document.getElementById("paginated-list");
            tr = table.getElementsByTagName("tr");
            for (i = 1; i < tr.length; i++) {
                alltags = tr[i].getElementsByTagName("td");
                isFound = false;
                for (j = 0; j < alltags.length; j++) {
                    td = alltags[j];
                    if (td) {
                        txtValue = td.textContent || td.innerText;
                        if (txtValue.toLowerCase().indexOf(filter) > -1) {
                            tr[i].style.display = "";
                            j = alltags.length;
                            isFound = true;
                        }
                    }
                }
                if (!isFound && tr[i].className !== "header") {
                    tr[i].style.display = "none";
                }
            }
        }
  
      <!-- Table Search Script Ends -->
      
      <!-- Table total row count and current page row count Script Starts -->
  
        var getTableRowCount = function(tableNode) {
            var tbody = tableNode.getElementsByTagName('tbody')[0];
            if (tbody) {
                return tbody.getElementsByTagName('tr').length;
            } else {
                return tableNode.getElementsByTagName('tr').length;
            }

        }

        var count = getTableRowCount(document.getElementById('paginated-list'));
        document.getElementById('rowsNumber').innerHTML = ' of  ' + count;

        document.getElementById("currNumber").innerHTML = 'Showing 1 - ' + count; 

     <!-- Table total row count and current page row count Script Ends -->
     
      <!-- Table Pagination Script Starts -->
 
const paginationNumbers = document.getElementById("pagination-numbers");
const paginatedList = document.getElementById("paginated-list");
const listItems = paginatedList.querySelectorAll("tbody tr");
const nextButton = document.getElementById("next-button");
const prevButton = document.getElementById("prev-button");

const paginationLimit = 2;
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage = 1;


const disableButton = (button) => {
    button.classList.add("disabled");
    button.setAttribute("disabled", true);
};

const enableButton = (button) => {
    button.classList.remove("disabled");
    button.removeAttribute("disabled");
};

const handlePageButtonsStatus = () => {
    if (currentPage === 1) {
        disableButton(prevButton);
    } else {
        enableButton(prevButton);
    }

    if (pageCount === currentPage) {
        disableButton(nextButton);
    } else {
        enableButton(nextButton);
    }
};

const handleActivePageNumber = () => {
    document.querySelectorAll(".pagination-number").forEach((button) => {
        button.classList.remove("active");
        const pageIndex = Number(button.getAttribute("page-index"));
        if (pageIndex == currentPage) {
            button.classList.add("active");
        }
    });
};

const appendPageNumber = (index) => {
    const pageNumber = document.createElement("button");
    pageNumber.className = "pagination-number";
    pageNumber.innerHTML = `${index}\${pageCount}`; //for adding total page number
    pageNumber.setAttribute("page-index", index);
    pageNumber.setAttribute("aria-label", "Page " + index);
    paginationNumbers.innerHTML=''
    paginationNumbers.appendChild(pageNumber);
};
    

const getPaginationNumbers = (theCurrentPage) => {
    for (let i = 1; i <= pageCount; i++) {
        theCurrentPage = theCurrentPage ?? 1
        if(i==theCurrentPage){appendPageNumber(i)}
    }
};

const setCurrentPage = (pageNum) => {
    currentPage = pageNum;
    if(currentPage===1){prevButton.disabled = true} // disable button when currentPage equal first page by pressing page number
    if(currentPage===pageCount){nextButton.disabled = true}// disable button when cureentPage equal last page by pressing page number
    handleActivePageNumber();
    handlePageButtonsStatus();

    const prevRange = (pageNum - 1) * paginationLimit;
    const currRange = pageNum * paginationLimit;

    listItems.forEach((item, index) => {
        item.classList.add("hidden");
        if (index >= prevRange && index < currRange) {
            item.classList.remove("hidden");
        }
    });
};

window.addEventListener("load", () => {
    getPaginationNumbers();
    setCurrentPage(1);

    prevButton.addEventListener("click", () => {
        setCurrentPage(currentPage - 1);
        if(currentPage===1){prevButton.disabled = true}// disable button when cureentPage equal first page 
        getPaginationNumbers(currentPage);
    });

    nextButton.addEventListener("click", () => {
        setCurrentPage(currentPage + 1);
        if(currentPage===pageCount){nextButton.disabled = true}// disable button when cureentPage equal last page 
        getPaginationNumbers(currentPage);
    });

    document.querySelectorAll(".pagination-number").forEach((button) => {
        const pageIndex = Number(button.getAttribute("page-index"));

        if (pageIndex) {
            button.addEventListener("click", () => {
                setCurrentPage(pageIndex);
            });
        }
    });
});

<!-- Table Pagination Script Ends -->
   .result {
        text-align: center;
        padding-bottom: 20px;
        width: 100%;
    }
    
      .canel-trains-grids {
        float: left;
        width: 100%;
        margin-bottom: 20px;
    }
    
    .canel-trains-grids .left-cancel {
        float: left;
        width: 60%;
        margin-top: 10px;
    }
    
    .canel-trains-grids .left-cancel span {
        float: left;
        font-size: 16px;
        background: #34A853;
        color: #fff;
        font-weight: 400;
        padding: 8px 8px;
        border-radius: 3px;
        text-align: left;
        line-height: 1.5em;
        width: auto;
    }
    
    .canel-trains-grids .right-cancel {
        float: right;
        width: 30%;
        margin-top: 10px;
    }
    
    .canel-trains-grids .right-cancel label {
        float: left;
        vertical-align: middle;
        line-height: 39px;
        font-size: 16px;
        color: #000;
        font-weight: 400;
    }
    
    .canel-trains-grids .right-cancel input {
        width: 230px;
        height: 22px;
        border: 1px solid #dae9f3;
        border-radius: 5px;
        padding: 8px 8px 8px 16px;
        float: right;
    }
    
    .canel-trains-grids .right-cancel input:focus {
        outline: none;
    }
    

 /* Responsive Table Start */
    
    .rstable {
        width: 100%;
        margin: 0 auto;
        padding: 16px 0px;
    }
    
    .rstable table {
        font-family: calibri, sans-serif;
        border-collapse: collapse;
        font-size: 16px;
        width: 100%;
        font-weight: 400;
    }
    
    .rstable tr {
        border-bottom: 1px solid #ccc;
    }
    
    .rstable tr td {
        text-align: left;
        padding: 9px;
        color: #333;
    }
    
    .rstable th {
        text-align: left;
        padding: 10px 9px;
        background: #004287;
        color: #fff;
        font-weight: 500;
    }
    
    .rstable tr:nth-child(even) {
        background: #f9fbfdc4;
    }
    
    .rstable tr:nth-child(odd) {
        background: #dae9f3;
    }
    
    .rstable tr td a {
        color: #004287;
        font-size: 16px;
    }
    
    @media (min-width: 768px) and (max-width: 1023px) {
        .rstable table {
            font-size: 15px;
        }
    }
    
    @media screen and (max-width: 767px) {
        .rstable table {
            font-size: 16px;
            font-weight: 400;
        }
        .rstable thead {
            display: none;
        }
        .rstable td:first-child {
            text-align: left;
            display: inline-grid;
            width: 90%;
        }
        .rstable td {
            text-align: left;
            display: inline-grid;
            width: 26%;
            vertical-align: top;
            color: #333;
            font-weight: 400;
        }
        .rstable td:before {
            content: attr(data-title);
            font-weight: 500;
            padding-bottom: 5px;
            font-size: 16px;
            color: #000;
        }
    }
    
    @media (min-width: 280px) and (max-width: 319px) {
        .rstable td {
            width: 23%;
        }
    }
    /* Responsive Table Ends */ 

   .arrow-right,
        .arrow-left {
            display: block;
            margin: 10px auto;
            width: 8px;
            height: 8px;
            border-top: 2px solid #000;
            border-left: 2px solid #000;
        }
        
        .arrow-right {
            transform: rotate(135deg);
        }
        
        .arrow-left {
            transform: rotate(-45deg);
        }
        
        .hidden {
            display: none;
        }
        
        .pagination-container {
            width: calc(100% - 0rem);
            display: flex;
            align-items: center;
            position: relative;
            bottom: 0;
            padding: 0rem 0;
            justify-content: right;
            /* text-align: center; */
        }
        
.pagination-number, .pagination-button {
    font-family: calibri, sans-serif;
    font-size: 16px;
    background-color: transparent;
    border: none;
    margin: 0.1rem 0.1rem;
    cursor: pointer;
    height: 2rem;
    width: 2rem;
    border-radius: 0.2rem;
}
        
        .pagination-number:hover,
        .pagination-button:not(.disabled):hover {
            background: #fff;
        }
        
        .pagination-number.active {
            color: #fff;
            background: #0085b6;
        }
                    <!-- Result Start -->
                    
                    <div class="result">
                        <div class='canel-trains-grids'>
                            <div class='left-cancel'><span>22 Rajdhani Express Trains Listed</span>
                            </div>
                            <div class='right-cancel'>
                                <input type="text" id="myInput" onInput="myFunction()" placeholder='Enter Train Number'>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Result Table Starts -->
                    
                        <div class="rstable">
                        <table id="paginated-list">
                            <thead>
                                <tr>
                                    <th>Train</th>
                                    <th>Type</th>
                                    <th>Zone</th>
                                    <th>From</th>
                                    <th>Dep</th>
                                    <th>To</th>
                                    <th>Arr</th>
                                    <th>Dur</th>
                                    <th>Halts</th>
                                    <th>Runs On</th>
                                    <th>Dist</th>
                                    <th>Speed</th>
                                    <th>Classes</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td data-title="Train">15011 Kashi Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">97 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15012 Pushpak Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">96 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15013 Godan Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">95 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15014 Golden Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">94 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15015 Lucknow Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">93 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15016 SLN Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">92 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15017 Sitapur Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">91 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>
                                <tr>
                                    <td data-title="Train">15018 Darbhanga Express</td>
                                    <td data-title="Type">SuperFast</td>
                                    <td data-title="Zone">CR</td>
                                    <td data-title="From">LTT</td>
                                    <td data-title="Dep">15:30</td>
                                    <td data-title="To">GKP</td>
                                    <td data-title="Arr">06:15 +1 night</td>
                                    <td data-title="Dur">7h 55m</td>
                                    <td data-title="Halts">11</td>
                                    <td data-title="Runs On">S - T - T F -</td>
                                    <td data-title="Dist">632 km</td>
                                    <td data-title="Speed">90 km/hr</td>
                                    <td data-title="Classes">SL | 3A | 2A</td>
                                </tr>

                            </tbody>
                        </table>

                    </div>
                    
                    <div style="width: 100%; display: flex;align-items: center;">
                        <div style="text-align: left; width: 50%;">
                            <span id="currNumber"></span><span id="rowsNumber"></span>
                        </div>
                        <div class="pagination-container">
                            <button class="pagination-button" id="prev-button" aria-label="Previous page" title="Previous page">
                            <span class="arrow-left"></span>
                    </button>
                            <div id="pagination-numbers">
                            </div>
                            <button class="pagination-button" id="next-button" aria-label="Next page" title="Next page">
                            <span class="arrow-right"></span>
                        </button>

                        </div>
                    </div>
                    <!-- Result Table Ends -->

Variable is possibly undefined with Svelte “bind:this={}”

When I try to use Svelte’s bind:this attribute, I get this shown in vscode:

'cardGroup' is possibly 'undefined'.js(18048)

And when run, I get this error:

TypeError: Cannot read properties of undefined (reading 'childNodes')

I was originally working in Typescript where I got the error that the bound variable was not declared before usage.

Script:

    let cardGroup;
    let cardContainers = cardGroup.childNodes;
    console.log(cardContainers.length);

HTML:

<div class="cardGroup" bind:this={cardGroup}>
    [content]
</div>

It is entirely possible that I’m missing something but I haven’t found anything using this binding that isnt doing exactly what I am, from what I can tell.

items in flex are merging

Im making a website and all my items that should be in flex box containers are merging instead of going into columns.[enter [

https://i.stack.imgur.com/EGgEy.png
https://i.stack.imgur.com/7BSmO.png

I’ve tried everything I know of, from changing values max width all positions and I’ve tried changing the code, spacing in the flex CSS.

/* index */

.flex-container {
  display: flex;
  flex-wrap: wrap;
  /* Allow items to wrap to the next line */
  justify-content: space-around;
  /* Distribute items evenly along the main axis */
}


/* Add flex properties to the flex items (columns) */

.column {
  flex: 0 0 calc(33.33% - 20px);
  /* Set the flex property to allow flexibility and spacing */
  margin: 10px;
  /* Add margin for spacing between items */
}


/* Responsive design for smaller screens */

@media (max-width: 800px) {
  .flex-container {
    flex-direction: column;
    /* Change to a column layout on smaller screens */
    align-items: center;
    /* Center items along the cross-axis */
  }
  .column {
    flex: 0 0 calc(100% - 20px);
    /* Full width for columns on smaller screens */
  }
}

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #784c4d !important;
  overflow-x: hidden;
  overflow-y: auto;
}

header {
  background-color: #312729;
  color: #f56e77;
  padding: 30px;
  text-align: center;
  z-index: 1;
}

.indexHeader {
  background-color: #312729;
  color: #f56e77;
  text-align: center;
  z-index: 1;
}

footer {
  background-color: #593e41;
  color: #b75d6b;
  padding: 10px;
  text-align: center;
  position: fixed;
  bottom: 0;
  width: 100%;
}


/* Side button open menu */

#openbutton {
  border-radius: 5px;
  background-color: #312729;
  color: #f2f2f2;
  padding: 15px;
  width: 5px;
  height: 20px;
  position: -webkit-sticky;
  position: sticky;
  top: 70px;
}


/* Side navigation menu */

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #251e20;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.5s;
}


/* The navigation menu links */

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #572d33;
  display: block;
  transition: 0.3s;
}


/* Mouse over the navigation links, change their color */

.sidenav a:hover {
  color: #ff8398;
}


/* Position and style the close button */

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}


/* Style page content */

#main {
  transition: margin-left .5s;
  padding: 20px;
}


/* On smaller screens, where height is less than 450px, change the style of the sidenav*/

@media screen and (max-height: 450px) {
  .sidenav {
    padding-top: 15px;
  }
  .sidenav a {
    font-size: 18px;
  }
}


/*home screen*/

.box {
  background-color: #593e41;
  width: 400px;
  height: 1200px;
  margin-left: -1.3%;
  margin-top: -140px;
  z-index: -1;
  position: absolute;
}

#rcorners1 {
  border-radius: 25px;
  background-color: #2e2526;
  padding: 200px;
  width: 1750px;
  height: 800px;
  margin-left: 45px;
}

#rcorners2 {
  border-radius: 200px;
  background-color: #f1ebf5;
  padding: 20px;
  width: 600px;
  height: 220px;
  margin-left: 78%;
  margin-top: -10%;
  z-index: 990;
}

.hiding {
  background-color: #784c4d;
  width: 50px;
  height: 220px;
  padding: 20px;
  margin-left: 85.2%;
  margin-top: -3.5%;
  z-index: 993;
}

img.profile {
  border-radius: 50%;
  width: 210px;
  height: 210px;
  margin-left: -0.7%;
  margin-top: -0.8%;
  position: absolute;
}

.name {
  color: #f56e77;
  max-width: 250px;
  margin-left: 11.3%;
  margin-top: 0%;
  position: absolute;
  width: 300px;
}

.adress {
  color: #897071;
  margin-left: 70%;
  margin-top: 0.4%;
  position: absolute;
}

.textwriting,
p {
  overflow: hidden;
  /* Ensures the content is not revealed until the animation */
  border-right: .15em solid #f56e77;
  /* The typwriter cursor */
  white-space: nowrap;
  /* Keeps the content on a single line */
  margin: 0 auto;
  /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15px;
  /* Adjust as needed */
  animation: typing 3.5s steps(40, end), blink-caret .75s step-end 3.5s 1 forwards;
  /* Use forwards to keep the last style applied after animation ends */
}


/* The typing effect */

@keyframes typing {
  from {
    width: 0
  }
  to {
    width: 100%
  }
}

@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: #f56e77;
  }
  90%,
  100% {
    border-color: transparent;
  }
  /* Hide the cursor after typing is done */
}

.objective {
  background-color: #f1ebf5;
  width: 595px;
  margin-left: 23.5%;
  margin-top: -14%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.education {
  background-color: #f1ebf5;
  width: 595px;
  margin-left: 23.5%;
  margin-top: 5%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.work_Experience {
  background-color: #f1ebf5;
  width: 595px;
  margin-left: 23.5%;
  margin-top: 14%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.skills {
  background-color: #f1ebf5;
  width: 235px;
  margin-left: 69.5%;
  margin-top: 4%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.certifications {
  background-color: #f1ebf5;
  width: 470px;
  margin-left: 57%;
  margin-top: 13%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.languages {
  background-color: #f1ebf5;
  max-width: 280px;
  margin-left: 57%;
  margin-top: 4%;
  padding-left: 20px;
  padding-right: 100px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.references {
  background-color: #f1ebf5;
  width: 590px;
  margin-left: -9.5%;
  margin-top: -14%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.additional_Information {
  background-color: #f1ebf5;
  width: 590px;
  margin-left: -9.5%;
  margin-top: -7%;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  border-radius: 5px;
  position: absolute;
}

.StarRating1 {
  margin-left: 35%;
  margin-top: -25%;
  position: absolute;
  width: 50%;
}

.StarRating2 {
  margin-left: 29%;
  margin-top: -16%;
  position: absolute;
  width: 50%;
}

.StarRating3 {
  margin-left: 24%;
  margin-top: -7.9%;
  position: absolute;
  width: 50%;
}

.checked {
  color: #ffc65d;
}
<div class="boxWrapper">
  <div id="rcorners1">
    <div id="rcorners2">
      <h1 class="name">name</h1>
      <img class="profile" src="img.png" alt="Avatar" />
      <div class="hiding"></div>
    </div>

    <div>
      <p1 class="adress" class="flexcontainer">Location: </p1>
    </div>

    <div class="textwriting"></div>

    <span class="type" style="--n: 53"></span>

    <!-- CV texts -->
    <div class="objective" class="flexcontainer">
      <h3>Objective</h3>
      <p>
        A driven and innovative professional seeking to leverage my expertise
        <br> in programming, software development, and graphic design to contribute to a <br> dynamic team environment. <br>
        <br> With a passion for crafting efficient and visually captivating solutions, <br> I am committed to delivering high-quality work that aligns with the objectives <br> of my employer. Eager to apply my skills and creativity to tackle challenging
        <br> projects while continuously enhancing my knowledge <br> in the ever-evolving field of technology.
      </p>
    </div>

    <div class="education" class="flexcontainer">
      <h3>Education</h3>
      <p>
        I taught myself coding when I was 15yrs old I've never been able to stop. <br> I am currently studing at brogymnasiet in kristinehamn since 2023 and so far <br> it's been a breeze. Since I knew alot of programing its been easy and
        <br> I'm eager to learn more and I hope to do so through your help!
      </p>
    </div>

    <div class="work_Experience" class="flexcontainer">
      <h3>Work Experience</h3>
      <p>To be added...</p>
    </div>

    <div class="skills" class="flexcontainer">
      <h3>Skills</h3>
      <p1>HTML, HTML5, CSS, JS, React.JS, C#, C++, AutoCAD, Art</p1>
    </div>

    <div class="certifications" class="flexcontainer">
      <h3>Certifications</h3>
      <p>To be added...</p>
    </div>

    <div class="languages" class="flexcontainer">
      <h3>Languages</h3>
      <p1>Swedish:<br> English:
        <br> Thai:
      </p1>

      <!-- Star ratings -->
      <div class="StarRating1">
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
      </div>

      <div class="StarRating2">
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star"></span>
        <span class="fa fa-star"></span>
      </div>

      <div class="StarRating3">
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star checked"></span>
        <span class="fa fa-star"></span>
        <span class="fa fa-star"></span>
        <span class="fa fa-star"></span>
      </div>
    </div>

    <div class="references" class="flexcontainer">
      <h3>References</h3>
      <p>To be added...</p>
    </div>

    <div class="additional_Information" class="flexcontainer">
      <h3>Additional Information</h3>
      <p>
        In the past, I pursued art, including drawing, painting, and digital design. <br> This background influences my approach to programming, allowing me to
        <br> incorporate aesthetics and user experience into my projects effectively.
      </p>
    </div>
    ``` and the css ``` ```

why JavaScript SPA application not rendering

I’m trying to build an SPA application but it’s not rendering the “renderItem” and “renderTotalPrice” functions. I will not add the style file
note that when I was just using one js file it was rendering when I separated the files into 4 files it stops render the mentioned two functions
I know that I need to create a js file for the navbar instead of coding it in the HTML file but for the next step after I solve this issue.

the code is:

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <title>Flying Dutchman</title>
  </head>
  <body>
    <!-- Navigation Bar -->
    <nav>
      <ul>
        <!-- Logo -->
        <li id="logo">
          <img src="flying_logo.png" alt="" />
        </li>

        <!-- Navigation Links -->
        <li><a href="#" id="drinksLink">Drinks</a></li>
        <li><a href="#" id="foodLink">Food</a></li>
        <li id="blankSpace"><a href=""></a></li>

        <!-- Login Button -->
        <li><button id="loginBtn">Login</button></li>
      </ul>
    </nav>

    <!-- Main Content Container -->
    <div id="container">
      <!-- Drinks and Foods Section -->
      <div id="drinksFoods">
        <!-- Content for Drinks and Foods will be dynamically populated here -->
      </div>

      <!-- Payment Section -->
      <div id="payment">
        <!-- Content for payment will be dynamically populated here -->
        
      </div>
    </div>

    <!-- JavaScript Controller -->
    <script src="./controller.js"></script>
  </body>
</html>

controller.js:


import model from "./model.js";
import itemView from "./itemView.js";
import paymentPanel from "./paymentPanel.js"; 
// Controller
const controller = {
  /**
   * Controller module responsible for managing user interactions and updating the model and view.
   *
   * @type {Object}
   */

  /**
   * Handles data transfer during dragstart and sets the dragged item.
   *
   * @param {Event} event - The dragstart event.
   * @param {Object} item - The item being dragged.
   */
  dragStart: function (event, item) {
    event.dataTransfer.setData("text/plain", JSON.stringify(item));
  },

  /**
   * Prevents the default behavior to enable drop in the dragenter event.
   *
   * @param {Event} event - The dragenter event.
   */
  dragEnter: function (event) {
    event.preventDefault();
  },
  /**
   * Prevents the default behavior to enable drop in the dragover event.
   *
   * @param {Event} event - The dragover event.
   */

  dragOver: function (event) {
    event.preventDefault();
  },
  /**
   * Handles the drop operation, adding the dropped item to the order summary.
   *
   * @param {Event} event - The drop event.
   */
  drop: function (event) {
    event.preventDefault();

    const data = event.dataTransfer.getData("text/plain");
    const droppedItem = JSON.parse(data);

    model.selectedItems.push(droppedItem);
    model.total += droppedItem.price;
    paymentPanel.renderTotalPrice();
  },
  /**
   * Initializes the application, sets up event listeners, and renders initial content.
   */
  init: function () {
    itemView.renderItems(model.drinkItems, "drinksFoods");
    paymentPanel.renderTotalPrice();

    document
      .getElementById("drinksLink")
      .addEventListener("click", function () {
        itemView.renderItems(model.drinkItems, "drinksFoods");
      });

    document.getElementById("foodLink").addEventListener("click", function () {
      paymentPanel.renderItems(model.foodItems, "drinksFoods");
    });

    document
      .getElementById("checkoutBtn")
      .addEventListener("click", function () {
        alert("Processing payment. Total amount: $" + model.total.toFixed(2));
      });

    const orderSummary = document.getElementById("orderSummary");
    orderSummary.addEventListener("dragenter", controller.dragEnter);
    orderSummary.addEventListener("dragover", controller.dragOver);
    orderSummary.addEventListener("drop", controller.drop);
  },

  /**
   * Adds an item to the cart, updates the model, and triggers a view update.
   *
   * @param {Object} item - The selected item to be added to the cart.
   */
  addToCart: function (item) {
    model.selectedItems.push(item);
    model.total += item.price;
    paymentPanel.renderTotalPrice();
  },
};

export default controller;
// Initialize the application
controller.init();

model.js

const model = {
  /**
   * Initializes the model with data for drink and food items, selected items, and the total cost.
   */
  drinkItems: [
    {
      id: 1,
      name: "Drink 1",
      price: 5.99,
      details: "Refreshing beverage",
    },
    {
      id: 2,
      name: "Drink 2",
      price: 3.99,
      details: "Crisp and cool",
    },
    {
      id: 3,
      name: "Drink 3",
      price: 4.99,
      details: "Satisfying drink",
    },
    {
      id: 4,
      name: "Drink 4",
      price: 6.99,
      details: "Delicious drink",
    },
    {
      id: 5,
      name: "Drink 5",
      price: 7.99,
      details: "Tasty drink",
    },
    {
      id: 6,
      name: "Drink 6",
      price: 8.99,
      details: "Refreshing beverage",
    },
    {
      id: 7,
      name: "Drink 7",
      price: 9.99,
      details: "Crisp and cool",
    },
    {
      id: 8,
      name: "Drink 8",
      price: 10.99,
      details: "Satisfying drink",
    },
    {
      id: 9,
      name: "Drink 9",
      price: 11.99,
      details: "Delicious drink",
    },
    {
      id: 10,
      name: "Drink 10",
      price: 12.99,
      details: "Tasty drink",
    },
    {
      id: 11,
      name: "Drink 11",
      price: 13.99,
      details: "Refreshing beverage",
    },
    {
      id: 12,
      name: "Drink 12",
      price: 14.99,
      details: "Crisp and cool",
    },
    {
      id: 13,
      name: "Drink 13",
      price: 15.99,
      details: "Satisfying drink",
    },
    {
      id: 14,
      name: "Drink 14",
      price: 16.99,
      details: "Delicious drink",
    },
    {
      id: 15,
      name: "Drink 15",
      price: 17.99,
      details: "Tasty drink",
    },
    // Add more items as needed
  ],
  foodItems: [
    { name: "Food 1", price: 7.99, details: "Delicious meal" },
    { name: "Food 2", price: 9.99, details: "Satisfying dish" },
    { name: "Food 3", price: 8.99, details: "Tasty food" },
    { name: "Food 4", price: 10.99, details: "Delicious food" },
    { name: "Food 5", price: 11.99, details: "Satisfying food" },
    { name: "Food 6", price: 12.99, details: "Tasty dish" },
    { name: "Food 7", price: 13.99, details: "Delicious dish" },
    { name: "Food 8", price: 14.99, details: "Satisfying meal" },
    { name: "Food 9", price: 15.99, details: "Tasty meal" },
    { name: "Food 10", price: 16.99, details: "Delicious meal" },
    { name: "Food 11", price: 17.99, details: "Satisfying dish" },
    { name: "Food 12", price: 18.99, details: "Tasty food" },
    { name: "Food 13", price: 19.99, details: "Delicious food" },
    { name: "Food 14", price: 20.99, details: "Satisfying food" },
    { name: "Food 15", price: 21.99, details: "Tasty dish" },
    // Add more food items as needed
  ],
  selectedItems: [],
  total: 0,
};

export default model;

itemView.js

import { controller } from "./controller.js";
import { model } from "./model.js";
const itemView = {
  /**
   * Renders a list of items in a specified container.
   *
   * @param {Object[]} items - The array of items to be rendered.
   * @param {string} containerId - The ID of the container element in the HTML.
   */

  //itemView

  renderItems: function (items, containerId) {
    const container = document.getElementById(containerId);
    container.innerHTML = "";

    items.forEach((item) => {
      const itemBox = document.createElement("div");
      itemBox.classList.add("itemBox");
      itemBox.setAttribute("draggable", true); // Make the item box draggable

      const itemName = document.createElement("p");
      itemName.textContent = `Name: ${item.name}`;

      const itemDetails = document.createElement("p");
      itemDetails.textContent = `Price: $${item.price.toFixed(2)}`;

      const itemDescription = document.createElement("p");
      itemDescription.textContent = `Details: ${item.details}`;

      itemBox.appendChild(itemName);
      itemBox.appendChild(itemDetails);
      itemBox.appendChild(itemDescription);

      itemBox.addEventListener("click", function () {
        controller.addToCart(item);
      });
      itemBox.addEventListener("dragstart", function (event) {
        controller.dragStart(event, item);
      });

      container.appendChild(itemBox);
    });
  },

};

export default itemView;

paymentPanel.js

import { model } from "./model.js";
import { controller } from "./controller.js";
const paymentPanel = {
  /**
   * Renders the total price in the HTML element with the ID "totalPrice".
   */
  // paymentPanel
  renderTotalPrice: function () {
    const paymentPanel = document.getElementById("payment");
    let orderSummary = document.getElementById("orderSummary");
    let totalPriceElement = document.getElementById("totalPrice");
    let checkoutBtn = document.getElementById("checkoutBtn");

    // If orderSummary doesn't exist, create and append it to the paymentPanel
    if (!orderSummary) {
      orderSummary = document.createElement("div");
      orderSummary.textContent = "Order Summary";
      orderSummary.id = "orderSummary";
      paymentPanel.appendChild(orderSummary);
    }

    // Clear existing content in orderSummary
    orderSummary.innerHTML = "";

    // Display selected items with counts in orderSummary
    const itemCounts = {}; // Moved the itemCounts object outside the loop
    const renderedItems = {}; // Keep track of items that have been rendered

    model.selectedItems.forEach((selectedItem) => {
      const itemId = selectedItem.id;

      // If the item is already in the orderSummary, update the count
      if (itemCounts[itemId]) {
        itemCounts[itemId]++;
      } else {
        itemCounts[itemId] = 1;
      }

      // Check if the item has been rendered before
      if (!renderedItems[itemId]) {
        // Create a new element for the item with the correct count
        const selectedItemElement = document.createElement("p");
        selectedItemElement.textContent = `${selectedItem.name} x${
          itemCounts[itemId]
        } - $${selectedItem.price.toFixed(2)}`;
        orderSummary.appendChild(selectedItemElement);

        // Mark the item as rendered
        renderedItems[itemId] = true;
      }
    });

    // Update the content of totalPriceElement
    if (!totalPriceElement) {
      totalPriceElement = document.createElement("p");
      totalPriceElement.id = "totalPrice";
      paymentPanel.appendChild(totalPriceElement);
    }
    totalPriceElement.textContent = `Total: $${model.total.toFixed(2)}`;

    // If checkoutBtn doesn't exist, create and append it to the paymentPanel
    if (!checkoutBtn) {
      checkoutBtn = document.createElement("button");
      checkoutBtn.textContent = "Checkout";
      checkoutBtn.id = "checkoutBtn";
      paymentPanel.appendChild(checkoutBtn);
    }
  },
};

export default paymentPanel;

Strange issue using CryptoJS, encrypts fine but decrypts just shows a blank file

I’m creating a browser based Django app that allows a user to upload some files to encrypt and then to decrypt using a password.

I have managed to get the encryption part working but when decrypting the files all return blank.

I’ve read through the CryptoJS docs and searched around but can’t find a solution that works. I’m sure this is just a minor mistake on my behalf but would really appreciate the help.

Please ignore the public/private key encryption stuff, one problem at a time :’)

// Event listener for encrypt button click
document.getElementById('encryptBtn').addEventListener('click', function() {
  // Retrieve encryption mode, encryption type, and password from input fields
  var mode = document.getElementById('modeSelect').value;
  var encryptionType = document.getElementById('encryptionType').value;
  var password = document.getElementById('password').value;

  // Retrieve selected files
  var files = document.getElementById('fileInput').files;
  // Create a new JSZip instance
  var zip = new JSZip();
  // Total number of files to process
  var totalFiles = files.length;
  // Counter to track processed files
  var filesProcessed = 0;

  // Initialize SweetAlert2 progress popup
  Swal.fire({
    title: mode === 'encrypt' ? 'Encrypting Files' : 'Decrypting Files',
    html: 'Processing: 0 / ' + totalFiles,
    allowOutsideClick: false,
    didOpen: () => {
      Swal.showLoading();
    }
  });

  // Loop through each file
  for (var i = 0; i < totalFiles; i++) {
    // Use a closure to capture the file variable
    (function(file) {
      var reader = new FileReader();

      // Event handler for when file is loaded
      reader.onload = function(event) {
        var data = event.target.result;
        var processedData;

        try {
          if (mode === 'encrypt') {
            // Encrypt the file data
            processedData = encryptData(data, encryptionType, password);
          } else {
            // Decrypt the file data
            processedData = decryptData(data, encryptionType, password);
          }

          // Add the processed data to the zip
          zip.file(file.name, processedData);
        } catch (error) {
          // Handle errors
          console.error('Error processing file:', error);
        }

        filesProcessed++;

        // Update progress in the SweetAlert2 popup
        Swal.update({
          html: 'Processing: ' + filesProcessed + ' / ' + totalFiles
        });

        // If all files are processed, generate the zip and trigger download
        if (filesProcessed === totalFiles) {
          zip.generateAsync({
            type: 'blob'
          }).then(function(content) {
            // Close SweetAlert2 popup
            Swal.close();
            // Trigger download of the encrypted/decrypted zip file
            saveAs(content, mode === 'encrypt' ? 'encrypted_files.zip' : 'decrypted_files.zip');
          });
        }
      };

      // Read file as array buffer
      reader.readAsArrayBuffer(file);
    })(files[i]); // Pass the current file to the closure
  }
});

// Function to encrypt data based on encryption type
function encryptData(data, encryptionType, password) {
  if (encryptionType === 'password') {
    var parsedData = CryptoJS.enc.Utf8.parse(data);
    var encrypted = CryptoJS.AES.encrypt(parsedData, password).toString();
    return encrypted;
  } else if (encryptionType === 'publicKey') {
    // Implement encryption using public key
    // Example: Encrypt data using public key
    return data;
  } else {
    return data;
  }
}

// Function to decrypt data based on encryption type
function decryptData(data, encryptionType, password) {
  if (encryptionType === 'password') {
    // Decrypt data using AES 256 decryption
    var decrypted = CryptoJS.AES.decrypt(data, password);
    var decryptedData = decrypted.toString(CryptoJS.enc.Utf8);
    console.log(decryptData)
    return decryptedData;
  } else if (encryptionType === 'publicKey') {
    // Implement decryption using public key
    // Example: Decrypt data using public key
    return data;
  } else {
    // If encryption type is not recognized, return original data
    return data;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Struggling in accessing row id in JS LWC

I have created a custom html table having one input “Quanity” field. Need to access each row with quantity data in JS. For that I am trying to access the rowId but getting undefined. Need help here to find out the missing thing.




Here is my JS code :
 

handleQuantityChange(event) {
        const rowId = event.target.dataset.id;
                 console.log('rowId=>'+JSON.stringify(rowId));
                 
        const value = parseInt(event.target.value, 10);
                  console.log('value=>'+value);`your text`
        this.addedProducts = this.addedProducts.map(product =>
            product.Id === rowId ? { ...product, Quantity: value } : product
        );
        console.log('sss qty  '+JSON.stringify( this.addedProducts));
    

`HTML:

<template for:each={addedProducts} for:item="product">
                                                        <tr key={product.Id} id={product.Id}>
                                                                <td data-label="Name" class="slds-size_1-of-4">
                                                                        <div class="slds-truncate">{product.Name}</div>
                                                                </td>
                                                                <td data-label="Product Code" class="slds-size_1-of-4">
                                                                        <div class="slds-truncate">{product.ProductCode}</div>
                                                                </td>
                                                                <td data-label="List Price" class="slds-size_1-of-4">
                                                                        <div class="slds-truncate" >{product.List_Price__c} &euro;</div>
                                                                </td>
                                                                <td data-label="Discount" class="slds-size_1-of-4"  data-id={product.id}>
                                                                        <div class="slds-truncate">                                                                              
                                                                                <input type="number" value={Quantity} data-id={product.id} onclick={handleQuantityChange} >
                                                                        </div>
                                                                </td>

                                                                <td data-label="DiscountType" class="slds-size_1-of-4">

                                                                        <!-- Use lightning-combobox for discount type -->
                                                                        <lightning-combobox name="DiscountType" value={product.DiscountType} options={discountTypeOptions}  data-product-id={product.Id}></lightning-combobox>
                                                                </td>
                                                                <td data-label="Discount" class="slds-size_1-of-4">
                                                                        <div class="slds-truncate">
                                                                                <input type="number" value={Discount} onchange={handleDiscountChange} data-product-id={product.Id}>
                                                                        </div>
                                                                </td>
                                                                <td data-label="Net Price" class="slds-size_1-of-4">
                                                                        <div class="slds-truncate" >{NetPrice} &euro;</div>
                                                                </td>
                                                        </tr>
                                                </template>

How to remove value from vue Inertia form when there is a conditions

So I have this form that changes whenever user choose which one field they want to fill like this
new data
existing data

when the user choose to fill new data, they input a new code, and if the user want to fill the data using existing code they will choose in the select field

the problem is there is no telling whether user choose using new data or existing data, the form fields always fill it both, I have tried it using an conditional based on the radio group value (true or false), so I can split it later in controller, but the radio value always true because it takes the value from the default declaration

export default {
    components: {
        AuthenticatedLayout,
        PrimaryButton,
        TextInput,
        InputLabel,
    },
    setup() {
        const radioCode = ref(true);
        const form = useForm({
            newData: radioCode,
            image: "",
            codeText: "",
            codeSelect: "",
            description: "",
            category: "",
            woodtype: "",
            width: "",
            depth: "",
            height: "",
            stock: "",
            price: "",
        });

        const submit = () => {
            form.post(route("input.create"));
        };

        return { radioCode, submit, form };
    },
    methods: {
        onChange(event) {
            this.radioCode = !this.radioCode;
            // console.log(this.radioCode);
        },
    },
};

Is there any way to do a conditional check when the radio is true, the form data will sends codeText and the rest of data without codeSelect , and when the radio is false the form data will sends codeSelect and removes codeText and sends all the rest of data?

the form

<form @submit.prevent="submit">
                                <div
                                    class="border-1 border-yellow-400 p-2 flex flex-row"
                                >
                                    <div
                                        class="border-1 border-green-500 w-[50%] items-center p-2"
                                    >
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Image :</h1>
                                            <input
                                                id="image"
                                                v-on:change="form.image"
                                                type="file"
                                                class="file-input file-input-sm rounded-md file-input-bordered file-input-primary w-full max-w-xs"
                                            />
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Code :</h1>
                                            <div v-if="radioCode">
                                                <input
                                                    id="codeText"
                                                    v-model="form.codeText"
                                                    type="text"
                                                    placeholder="Type here"
                                                    class="input input-bordered input-primary w-full max-w-xs"
                                                />
                                            </div>
                                            <div v-else>
                                                <select
                                                    id="codeSelect"
                                                    v-model="form.codeSelect"
                                                    class="select select-md select-primary w-full max-w-xs"
                                                >
                                                    <option disabled selected>
                                                        Existing Code
                                                    </option>
                                                    <option>TW-01</option>
                                                    <option>TW-02</option>
                                                    <option>TW-03</option>
                                                    <option>TW-04</option>
                                                </select>
                                                <!-- Radio Group -->
                                            </div>
                                            <div class="ml-5 flex flex-col">
                                                <div class="flex flex-row">
                                                    <input
                                                        type="radio"
                                                        name="radioCode"
                                                        class="mb-2 radio radio-sm radio-primary bg-inherit enabled:hover:border-info enabled:checked:bg-primary"
                                                        value="new"
                                                        @change="
                                                            onChange($event)
                                                        "
                                                        checked
                                                    />
                                                    <label
                                                        for="radio"
                                                        class="ml-2"
                                                        >New data</label
                                                    >
                                                </div>
                                                <div class="flex flex-row">
                                                    <input
                                                        type="radio"
                                                        name="radioCode"
                                                        class="radio radio-sm radio-primary bg-inherit enabled:hover:border-info enabled:checked:bg-primary"
                                                        value="exist"
                                                        @change="
                                                            onChange($event)
                                                        "
                                                    />
                                                    <label
                                                        for="radio"
                                                        class="ml-2"
                                                        >Existing data</label
                                                    >
                                                </div>
                                            </div>
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Description :</h1>
                                            <input
                                                id="description"
                                                v-model="form.description"
                                                type="text"
                                                placeholder="Type here"
                                                class="input input-bordered input-primary w-full max-w-xs"
                                            />
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Category :</h1>
                                            <select
                                                id="category"
                                                v-model="form.category"
                                                class="select select-md select-primary w-full max-w-xs"
                                            >
                                                <option disabled selected>
                                                    Insert category
                                                </option>
                                                <option>Indoor</option>
                                                <option>Outdoor</option>
                                                <option>Handicraft</option>
                                                <option>Root</option>
                                            </select>
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Wood Type :</h1>
                                            <select
                                                id="woodtype"
                                                v-model="form.woodtype"
                                                class="select select-md select-primary w-full max-w-xs"
                                            >
                                                <option disabled selected>
                                                    Insert wood type
                                                </option>
                                                <option>Teak Wood</option>
                                                <option>Tiger Wood</option>
                                                <option>Mahogany Wood</option>
                                                <option>Root</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div
                                        class="border-1 border-green-500 w-[50%] items-center p-2"
                                    >
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Width :</h1>
                                            <input
                                                id="width"
                                                v-model="form.width"
                                                type="text"
                                                placeholder="Type here"
                                                class="input input-bordered input-primary w-full max-w-xs"
                                            />
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Depth :</h1>
                                            <input
                                                id="depth"
                                                v-model="form.depth"
                                                type="text"
                                                placeholder="Type here"
                                                class="input input-bordered input-primary w-full max-w-xs"
                                            />
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Height :</h1>
                                            <input
                                                id="height"
                                                v-model="form.height"
                                                type="text"
                                                placeholder="Type here"
                                                class="input input-bordered input-primary w-full max-w-xs"
                                            />
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Stock :</h1>
                                            <input
                                                id="stock"
                                                v-model="form.stock"
                                                type="text"
                                                placeholder="Type here"
                                                class="input input-bordered input-primary w-full max-w-xs"
                                            />
                                        </div>
                                        <div
                                            class="flex flex-row p-2 border-1 border-cyan-300"
                                        >
                                            <h1 class="m-2">Price :</h1>
                                            <input
                                                id="price"
                                                v-model="form.price"
                                                type="text"
                                                placeholder="Type here"
                                                class="input input-bordered input-primary w-full max-w-xs"
                                            />
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <PrimaryButton
                                        class="ml-4"
                                        :class="{
                                            'opacity-25': form.processing,
                                        }"
                                        :disabled="form.processing"
                                    >
                                        Input
                                    </PrimaryButton>
                                </div>
                            </form>

the js script(vue)

<script>
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout.vue";
import PrimaryButton from "@/Components/PrimaryButton.vue";
import TextInput from "@/Components/TextInput.vue";
import InputLabel from "@/Components/InputLabel.vue";
import { Link, useForm } from "@inertiajs/vue3";
import { ref } from "vue";
import InputError from "@/Components/InputError.vue";
export default {
    components: {
        AuthenticatedLayout,
        PrimaryButton,
        TextInput,
        InputLabel,
    },
    setup() {
        const radioCode = ref(true);
        const form = useForm({
            newData: radioCode,
            image: "",
            codeText: "",
            codeSelect: "",
            description: "",
            category: "",
            woodtype: "",
            width: "",
            depth: "",
            height: "",
            stock: "",
            price: "",
        });

        const submit = () => {
            form.post(route("input.create"));
        };

        return { radioCode, submit, form };
    },
    methods: {
        onChange(event) {
            this.radioCode = !this.radioCode;
            // console.log(this.radioCode);
        },
    },
};
</script>

Service Worker Cache PDF Responses MIssing Data

When I use URL.createObjectURL(blob) to display a PDF in the browser, there’s no way (that I have found) to include a file name. Therefore, when the user then goes to download what they see and like, the blob gibberish is all they get.

See? Gibberish.

Using a service worker and cached responses, however, I’m able to persist the file names to the new tabs.


// listen 
self.addEventListener('fetch', (event) => {
    event.respondWith((async () => {
        const store = await caches.open("/documents/");
        const req = event.request;
        const cached = await store.match(req);
        return cached || fetch(req);
    })());
});

// register
navigator.serviceWorker.register('docServiceWorker.js')
    .then(reg => { if (reg.installing) location.reload(); })
    .catch(console.error);

// clear previously cached files
(async () => {
    const store = await caches.open(utils.DOCUMENTS_SW_CACHE_NAME);
    const keys = await store.keys();
    for (const req of keys) {
        store.delete(req);
    }
})();

Now we're getting somewhere

Unfortunately, other pertinent file information appears to be missing. If I attempt to download the file it displays as not found. If I try to dig into the file properties the button is disabled. It seems that the file is there but not really there.

With URL.createObjectURL(blob), the file data is intact. The browser knows it’s a PDF and it can be downloaded, no problem.

Obv PDF is obv

Works!

I can select doc properties and view them:

See? Props

There they are

With the cached responses, we’re missing all of that.

Can't click doc props

On download

Not really there?

Any ideas why I might be losing response data when it’s cached in this fashion? Again, able to view the file and persist file name data, but can’t download.

How to are money without investment

Hello this problem was solved Hello I shak je and I am trying the win the iPhone and intresting prices so anybody help me and help jsksn sksnsbsj jsjs bs msns jsjs. Jsksbs jse jsksbe jeie jsjbejeisnsbsjisbebsjdbbsusbebueveheje jsjsbebejebeb

Why is my Node,js app redirecting me to the failureRedirect route no matter what?

I am making a simple login page using Node.js for back-end stuff and passport for authentication. To me all my code looks good and it looks like it should work. I even put it into chatGPT and it couldn’t find any problems, either. No matter the input for the login page, even if it is correct, I get redirected to the failureRedirect page. I know the passwords and emails are correct, even though they are hashed and salted, because I make them extremely simple 3 character passwords for testing purposes. I even seen the hashed password in my DB.

My approach to the problem is taking the submitted input from the user and salting it then hashing it, and storing it to the DB. Then I used the local passport strategy to handle the authentication process by comparing the form input to the user input and if it matches the user will be redirected to a certain page and if not they will be redirected to another page, just for testing purposes. I will include relevant code below to give you a better idea of how I approached this problem.

//my User model, exported correctly
const UserSchema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    email: {type: String, required: true},
    password: {type: String, required: true},
    posts: {type: Schema.Types.ObjectId, ref: "Post"}
})
// password hashing code & user creation
asyncHandler(async (req, res, next) => {
    try {
        // Hash the password
        const hashedPassword = await bcrypt.hash(req.body.password, 10);

        // Check if user with the provided email already exists
        const existingUser = await User.findOne({ email: req.body.email }).exec();

        if (existingUser) {
            return res.status(400).send('Email already exists. Please use a different one.');
        }

        // Create new user
        const user = new User({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email,
            password: hashedPassword // Use the hashed password
        });

        await user.save();

        // Redirect after successful registration
        res.redirect("/");
    } catch (err) {
        next(err);
    }
});
// snippet of my authentication 
function configurePassport(passport) {
    passport.use(new LocalStrategy( async (email, password, done) => {
      try {
        const user = await User.findOne({ email: email })
        if (!user) {
          //usernames do not match!
          return done(null, false, { message: "Incorrect username" })
        };
        const match = await bcrypt.compare(password, user.password)
        if (!match) {
            // passwords do not match!
            return done(null, false, { message: "Incorrect password" })
          }
        return done(null, user);
      } catch(err) {
        return done(err);
      };
    }));
}
  h1= title
  if user 
    h1 Welcome back #{user.firstName}
  else  
    form(action="/", method="post")  
      input(type="email", name="email", placeholder="email")
      input(type="password", name="password", placeholder="password")
      button(type="submit") Log In
    a(href="/register") Register Now
passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/register"
});

So I have included my code for my Schema initialization, user creation and password hashing, the user authentication, and even my login form using pug with the passport.authenticate code. I have tried almost everything and I am not sure where I am going wrong. This is such a simple app that I feel like it has to be something simple. Also the configurePassword function is imported and called in my main app as configurePassword(passport).

lookbehind alternative way

This code doesn’t work in safari 15, so need another way to solve it without lookbehind

const re = /(?<!\)(?<!-)-/g;
const str = '20-30--40\---50--60';
console.log(str.split(re));

output:

['20', '30', '-40\---50', '-60']

What this code does:
Need to split the string into parts.
For example.

"10-20" -> ['10', '20']

but need to split only the first ‘-‘ and keep all ‘-‘ before the value, i.e.

"10---20" -> ['10', '--20']

and finally, it should be possible to escape with :

"10---20--30"  -> ['10', '--20', '-30']
"10---20--30" -> ['10', '--20--30']

I don’t know much about regex, chatgpt and alternatives couldn’t help me.

Encrypt in JS and Decrypt in PHP using AES encryption algorithm in GCM and Base64 encoding

I am try to Encrypt data in JS and Decrypt it in PHP using AES encryption algorithm in GCM and Base64 encoding. But during decryption I always get false as result without any openssl error. I have verify the data during transmission at frontend and backend are the same. I have also added "ext-openssl": "*" to my composer.json file in my laravel. What could I be doing wrong that I don’t get back the result as decrypted.

Below is My encryption Method in Frontend with JS

async function encryptData(data, key) {
    const encoder = new TextEncoder();
    const encodedData = encoder.encode(data);
    // Ensure the key is 256 bits (32 bytes)
    if (key.length !== 32) {
        throw new Error('AES key must be 256 bits (32 bytes)');
    }
    const cryptoKey = await crypto.subtle.importKey('raw', new TextEncoder().encode(key), {
        name: 'AES-GCM'
    }, false, ['encrypt']);
    const iv = crypto.getRandomValues(new Uint8Array(12));
    const encrypted = await crypto.subtle.encrypt({
        name: 'AES-GCM',
        iv
    }, cryptoKey, encodedData);
    // Concatenate IV and encrypted data and convert to base64
    const combinedData = new Uint8Array(iv.length + encrypted.byteLength);
    combinedData.set(iv);
    combinedData.set(new Uint8Array(encrypted), iv.length);
    // Convert to base64 using btoa
    const base64String = btoa(String.fromCharCode.apply(null, combinedData));
    return base64String; // Return the base64 string without URL encoding
}

Below is the Submission of the Encrypted data in Frontend with JS

async function submitData() {
    var licence = $('#licence').val();
    const encryptionKey = '12345678901234567890123456789012';

    try {
        let encryptedLicence = await encryptData(licence, encryptionKey);

        var jsonData = {
            licence: encryptedLicence
        };

        var queryParams = Object.keys(jsonData)
            .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(jsonData[key]))
            .join('&');
        var targetUrl = 'submit?' + queryParams;
        window.location.href = targetUrl;
    } catch (error) {
        console.error('Error encrypting data:', error.message);
    }
}

Below is how I receive data Backend in Php

 public function formData(Request $request){                                           
 $key = '12345678901234567890123456789012';                     
 $data=$request->licence;                                       
 $decryptedProduct = self::decryptingMyData($data, $key);     
 dd($decryptedProduct);
 }

And Below is how I decrypt in Php

public function decryptingMyData($encryptedData, $key) {                                                          
// URL-decode the received data                                                                                 
$receivedData = urldecode($encryptedData);                                                                      
$decodedData = base64_decode($receivedData);                                                                    
$iv = substr($decodedData, 0, 12);                                                                              
$encryptedText = substr($decodedData, 12);                                                                      
$decrypted = openssl_decrypt($encryptedText, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv);                     
if ($decrypted === false) {                                                                                     
// Decryption failed                                                                                          
 $opensslError = openssl_error_string();                                                                      
 dd($decrypted ,$opensslError);                                                                                           
return decrypted;                                                                                                
}                                                                    
return $decrypted;                                                                                                                                    

html post code to array not working, normal post as single value in array is possible

Sorry but iam new to programming so maybe my explanation is not as expected, but always learning:


my html post via :

<form action="filestimer-settings.php" method="post" name="my_location">

normaly is working on my site into my php script.

just now if i want to post in an Array ‘i think it is multidimension maybe?’ it is not possible anymore.
so my problem is with the value of name=isha_rule and isha_value

this is my html code :

      <input type="input" min="0" class="form-control" name="isha_value" id="isha_value" 
                readonly      value="">
      <input type="radio" name="isha_rule" id="isha_rule_0" checked value="1"> 
            
       <input type="radio" name="isha_rule" id="isha_rule_1"  value="1"> 

and this is my php code, i want to insert the html extraction

/**
     * Rules for calculation 0 -> angle, 1-> minutes
     *
     * @var array
     */
    public $fajir_rule      = array(0, 15);
    public $maghrib_rule    = array(1, 0);
    public $isha_rule       = array(0, 15);

ofcourse i thought it is a problem for a multidimensinal array

but always stays at the value thats incl. in the php script

so what I have done sofar
with many values on html input form

<div class="form-group">
     <label>  
              <?php echo $langArray['Ishaa_Rule']; ?>
    </label>
       <div class="input-group">
              <input type="input" min="0" class="form-control" name="isha_value" id="isha_value" readonly value="">
           <span class="input-group-addon" style="width:60%">
             <input type="radio" name="isha_rule" id="isha_rule_0" checked value="1"> 
                <?php echo $langArray['Angle']; ?> &nbsp;
      <input type="radio" name="isha_rule" id="isha_rule_1"  value="1"> 
                <?php echo $langArray['Minute']; ?>                                  
           </span>

via //$decoder is just a json import from a file where i stored all the array code

//$settings->isha_rule =$decoder->{"isha_value"};

become

    /**
     * Rules for calculation 0 -> angle, 1-> minutes
     *
     * @var array
     */
    public $fajir_rule      = array(0, 15);
    public $maghrib_rule    = array(1, 0);
    public $isha_rule       = array(0, 15);

i have done already =array(“”,””) or ([],[]) and experimented but no changes.

but it always stands as nailed at 15, normaly i put at html side 12 in, but it never changed.
if i manualy change the setting at :

public $isha_rule = array(0, 15);

to 12 the code works correctly and does it calculations.

ofcourse i thought it is a problem for a multidimensinal array, that cant get the values from the html post

here are the dumpout of $_POST

|        [fajir_value] => String(2)  "12"
|        [fajir_rule] => String(1)  "0"
|        [maghrib_value] => String(1)  "0"
|        [maghrib_rule] => String(1)  "1"
|        [isha_value] => String(2)  "12"
|        [isha_rule] => String(1)  "1"

and the dumpout of $settings wich includes the -> fajir_rule, maghrib_rule, isha_rule, var

   [fajir_rule] => Array(2)
|        |        
|        |        [0] => Integer(1)  0
|        |        [1] => Integer(2)  15
|        |        

|        [maghrib_rule] => Array(2)
|        |        
|        |        [0] => Integer(1)  1
|        |        [1] => Integer(1)  0
|        |        

|        [isha_rule] => Array(2)
|        |        
|        |        [0] => Integer(1)  0
|        |        [1] => Integer(2)  15
|        |        

So I wanted the isha_value from html method=”post” // =12
overrides the value in the $settings -> isha_rule //is 15 must be 12

Here is the whole code that is involved, if needet from the sites:

<div class="input-group">
                                    <input type="input" min="0" class="form-control" name="isha_value" id="isha_value" readonly value="15">
                                    <span class="input-group-addon" style="width:60%">
                                    <input type="radio" name="isha_rule" id="isha_rule_0" checked value="1"> <?php echo $langArray['Angle']; ?> &nbsp;
                                    <input type="radio" name="isha_rule" id="isha_rule_1"  value="1"> <?php echo $langArray['Minute']; ?>                                   </span>
$settings->isha_rule   =$decoder->{"fajir_value"};

    /**
     * Rules for calculation 0 -> angle, 1-> minutes
     *
     * @var array
     */
    public $fajir_rule      = array(0, 15);
    public $maghrib_rule    = array(1, 0);
    public $isha_rule       = array(0, 15);
 /**
     * Setup the object
     *
     * @param Settings $settings
     */
    public function __construct(Settings $settings)
    {
        $this->settings = $settings;
        $this->calcMethod = $this->settings->method;

        $this->methodParams = array(
            $this->settings->fajir_rule[1],

            $this->settings->maghrib_rule[0],
            $this->settings->maghrib_rule[1],

            $this->settings->isha_rule[0],
            $this->settings->isha_rule[1]
        );

        $this->asrJuristic = $this->settings->juristic;

        $this->lat = $this->settings->latitude;
        $this->lng = $this->settings->longitude;
        $this->adjustHighLats = $this->settings->high_latitude;
        $this->timeFormat = $this->settings->time_format;
    }

How to mock BigQuery insert?

How can I mock BigQuery’s insert?

It is a fluent interface, which make it dificult to mock.

I tried this:

vi.mock('@google-cloud/bigquery', () => {
  return {
    BigQuery: vi.fn().mockImplementation(() => {
      return {
        dataset: vi.fn().mockImplementation(() => {
          return {
            table: vi.fn().mockImplementation(() => {
              return {
                insert: vi.fn(),
              }
            }),
          }
        }),
      }
    }),
  }
})

But I get the error:

TypeError: Cannot read properties of undefined (reading ‘table’)

On the line:

const table = dataset.table(BIGQUERY_ACTIVITIES_TABLE)