Setting the scrollbar position of a block element in HTML

I want to set the scrollbar position of a block to specific coordinates when the page is loaded.

The closest thing I found to this is the

window.scrollTo

method in JavaScript, which sets the scrollbar positions of the horizontal and vertical scrollbars of the whole page in the browser. This script can then be run when the page is loaded.

I want to do the same with a block like this:

<div>
    <p> lots of text </p>
<div>
<style>
    div {
        overflow: scroll;  
}
</style>

Why toggle is not working if I don’t add CSS?

I am an absolute beginner. I am trying to do this project on animated search bar where it toggles between buttons.

Before adding CSS, I was trying to click on the icons to toggle but it didn’t work. Then I added CSS and it is working just fine. I thought CSS is for styling HTML documents.

What am I not understanding here? Does toggling work when 2 icons are together, overlapping or something. Can someone explain what is going on?

Code Snippet
(GitHub Source)

const searchBarContainerEl = document.querySelector(".search-bar-container");

const magnifierEl = document.querySelector(".magnifier");

magnifierEl.addEventListener("click", () => {
  searchBarContainerEl.classList.toggle("active");
});
body {
  margin: 0;
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
  background-color: aliceblue;
}

.search-bar-container {
  display: flex;
  align-items: center;
  background-color: aliceblue;
  padding: 5px;
  width: 300px;
  height: 50px;
  border-radius: 50px;
  box-shadow: 6px 6px 10px rgba(0, 0, 0, 0.2), -6px -6px 10px rgba(255, 255, 255, 0.7);
  margin: 10px;
  position: relative;
  transition: width 1.5s;
}

.magnifier {
  width: 25px;
  cursor: pointer;
  position: absolute;
  left: 20px;
}

.mic-icon {
  width: 30px;
  position: absolute;
  right: 10px;
  transition: width 0.4s;
  transition-delay: 1s;
}

.input {
  background-color: transparent;
  border: none;
  margin: 10px 50px;
  width: 100%;
  outline: none;
  color: rgb(100, 100, 100);
  transition: width 1s;
  transition-delay: 0.5s;
}

.active.search-bar-container {
  width: 50px;
}

.active .input {
  width: 0;
}

.active .mic-icon {
  width: 0;
}
<div class="search-bar-container active">
  <img src="https://cdn4.iconfinder.com/data/icons/evil-icons-user-interface/64/magnifier-512.png" alt="magnifier" class="magnifier" />
  <input type="text" class="input" placeholder="Search ..." />
  <img src="https://cdn1.iconfinder.com/data/icons/google-s-logo/150/Google_Icons-25-512.png" alt="mic-icon" class="mic-icon" />
</div>

How can I handle async loading ‘on the fly’ in React?

I’m writing an app which is essentially in React (it’s part of a framework, but React is the basis). The app needs to load a list from an API, and then display all the items from that list to the user.

The user can select up to 3 items from the list. When an item is selected, I load more information about that item, and display that to the user.

The issue I have is that the additional information which needs to be loaded requires quite a bit of processing before it can be displayed, so I want to store the result each time (so that if the user selects, for instance, Item 1, Item 2 and Item 3, and then deselects Item 2, and then reselects Item 2, it doesn’t have to reload and process the info for Item 2 all over again).

I have the following:

function App() {
  const [allItems, setAllItems] = React.useState(null);  // Name and id of every item
  const [itemsShown, setItemsShown] = React.useState([]); // id of shown items
  const [itemsInfo, setItemsInfo] = {};  // Full details of items

  // Initialise by getting list of items
  React.useEffect(() => {
    const getAll = async () => {
      const res = await Api.getItems();
      setAllItems(res);
    };

    getAll();
  }, []);

  const loadItem = async (itemId) => {
      // If item is already loaded, return without doing anything
      if(itemsInfo[itemId]) return;

      // Load item details - this function also processes the data to get it into
      //  the correct format
      const details = await Api.getItem(itemId);

      // Now save the processed data
      setItemsInfo({...itemsInfo, [itemId] : details})
      
  }

  // Handle the user changing the selection of items
  // This goes through the selector, and checks whether each item is selected
  // Those items that are selected are added to the 'itemsShown' variable
  const handleChangeSelection = (e) => {
    const newShown = [];
    for (let ii = 0; ii < e.target.options.length; ii++) {
      if (e.target.options[ii].selected && newShown.length < MAX_SELECTED) {
        // This item is selected, so add its id to shown items list
        newShown.push(e.target.options[ii].value);

        // If we don't have the full details for this item yet, load it
        if(!itemsInfo[e.target.options[ii].value]) {
            loadItem(e.target.options[ii].value)
        }
      }
    }
    setItemsShown([...newShown]);
  };

  // DISPLAY

  // Show a selector with the list of items as options
  // Whenever the selection changes, handleChangeSelection is called
  // Underneath that, show details of the selected items
  return (
    <div>
      <Selector
         options={allItems}
         onChange={handleChangeSelection}
      />
        {itemsShown.map((item) => (
           <ShowItem
              key={item.id}
              item={itemsInfo[item.id] ? itemsInfo[item.id] : null}
           />
          )}
    </div>
  );
}

export default App;

What I’m aiming for here is that the page initially loads all available items, getting the id and name for each one and displays them in a selector. When the user selects one or more items in the selector, the handleChangeSelection function loops over the selector to see what’s currently selected, and adds the id of each selected item to itemsShown. It also checks that we’ve already pulled in the full details of that item by checking for the key in itemsInfo; if not, it loads those details. Once they’re loaded, it updates itemsInfo with the full details, which are arranged in itemsInfo by key, so it will look like this:

{ key1 : {... item 1 details}, key2 : {... item 2 details}, etc... }

Meanwhile, the render method goes through all the itemsShown; for each one, it instantiates the ShowItem component; if the item details are known then it passes them in; otherwise it passes in null.

The problem I have is that the time taken for items to load varies, and sometimes they overlap. So it might start to load Item 1, and then start to load Item 2. Then Item 1 completes, and it updates the itemsInfo state variable to add item 1 details; meanwhile, before that’s complete, Item 2 loads, and updates the original itemsInfo variable (without Item 1 in it, because that hasn’t updated yet) to add Item 2.

I’m not sure how to handle this, because I don’t know when the user is going to click on an item, or how quickly they’re going to click. Technically they could click on an Item and then unselect it, but I still want the item to load because it will have started anyway.

How do I get this to work?

How to Properly Pass the Filename in NestJS?

I’ve encountered an issue with the encoding of file names. The Cyrillic characters are getting lost.

I have an Expo application. I can send files when creating a certain item (see the function below):

export const updateTaskApi = async (
  id: string,
  taskData: TTask,
  files: TDataFilePicker[] | null,
) => {
  const headers = await createHeaders();
  headers['Content-Type'] = 'multipart/form-data';
  console.log('headers', headers);
  const formData = new FormData();
  formData.append('taskData', JSON.stringify(taskData));
  if (files) {
    files.forEach((file) => {
      console.log(file);
      formData.append(
        'files',
        {
          uri: file.filePickerUri,
          type: file.filePickerType,
          name: file.filePickerName,
          fileName: file.filePickerName,
        } as any,
      );
    });
  }
  console.log(formData);
  return await axios.put(`${basicUrl}/tasks`, formData, {
    withCredentials: true,
    headers,
  });
};

The files are sent to the backend, but when I decompose them there, instead of names like Аватар.jpg, I get just .jpg and sometimes with empty characters in front.

Here’s the controller:

@Put()
@HttpCode(HttpStatus.OK)
@UseInterceptors(FilesInterceptor('files'))
async updateTask(
  @Body() body: TaskFormData,
  @Req() request: Request,
  @UploadedFiles() files?: Array<Express.Multer.File>,
) {
  await verifyAuthorization(request);
  console.log('Request headers:', request.headers);
  if (!body.taskData) {
    throw new BadRequestException('Task object data is missing');
  }
  console.log('files from general', files);
  const updateTask = plainToInstance(TaskDto, JSON.parse(body.taskData));

  await this.tasksService.validateTaskPreparationData(updateTask);

  return await this.tasksService.updateTask(
    updateTask._id,
    updateTask,
    files,
  );
}

In the array of files, I see something like this:


files from general [
  {
    fieldname: 'files',
    originalname: '.jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    buffer: <Buffer ff d8 ff e2 0b f8 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 0b e8 00 00 00 00 02 00 00 00 6d 6e 74 72 52 47 42 20 58 59 5a 20 07 d9 00 03 00 1b ... 72888 more bytes>,
    size: 72938
  }
]  

It turns out that the originalname field comes with an error and has lost the Cyrillic text. Meanwhile, globally, the only things that could affect the request before it reaches the controller are validation (ValidationPipe) and cookieParser. Nothing else. I’ve racked my brain and can’t figure out what’s happening with the encoding and where it disappears.

I’ve already checked all the documentation, tried to find similar issues from other people, and changed the ways of sending files several times. Nothing helped.

The graph cannot be displayed

I have used vue js and vue chart js latest version until now.
I tried drawing a Bar graph and edited the main.js file as follows

import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip } from 'chart.js'
import { createApp } from 'vue'
import { Bar } from 'vue-chartjs'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

const BarChart = {
    name: 'BarChart',
    components: { Bar },
    data() {
        return {
            chartData: {
                labels: ['January', 'February', 'March'],
                datasets: [
                    {
                        label: 'Data One',
                        backgroundColor: '#f87979',
                        data: [40, 20, 12]
                    }
                ]
            }
        }
    },
    template: '<Bar :data="chartData" />'
}
createApp(BarChart).mount('#app')

I only edited the main.js file. The remaining files remain unchanged by default when the project is first created. Running the npm run serve command, the graph cannot be displayed and I receive the error when opening Developer Tools Unchecked runtime.lastError: The message port closed before a response was received.

I want to code the graph in the main.js file but don’t want the code in the .vue file, how do I update the code?

Scroll to slide in full page

I’m looking to have each of the full-page sections slide in and out on scroll as seen here on this page
The background should be sort of pinned, as the next page slides in over it.
Scroll should only trigger the slide in, and you cannot continuously scroll or scroll until the next slide is in full view.

How will I achieve that?

Below is my page so far

gsap.registerPlugin(ScrollTrigger)

gsap.utils.toArray("section").forEach((section, i) => {
  ScrollTrigger.create({
    trigger: section,
    start: "top top",
    pin: true,
    pinSpacing: false,
  })
})
::-webkit-scrollbar{
  display: none;
}
html,
body{
  margin: 0;
}
section {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
h1 {
  font-size: 40px;
  color: black;
  background-color: #f1f1f1a2;
  padding: 20px
}
<section style="background-image:url(https://i.postimg.cc/D0KBrP1f/bmw.jpg);">
  <h1>FIRST</h1>
</section>
<section style="background-image: url(https://i.postimg.cc/hGfycjSn/beatle.jpg);">
  <h1>SECOND</h1>

</section>
<section  style="background-image:url(https://i.postimg.cc/NjNJ3Tvb/retrocar1.jpg);">
  <h1>THIRD</h1>
</section>
<section style="background-image:url(https://i.postimg.cc/RCfYWNwV/hot.jpg);">
  <h1>FOURTH</h1>
</section>
<section style="background-image:url(https://i.postimg.cc/6p6bbcgy/tvretro.jpg);">
  <h1>FIFTH</h1>
</section>

Javascript redirects to a page when submitting a form

(Sorry for bad English)

How do I redirect to another page when User fills correctly a form ? location.href = "otherpage.html"; or location.replace("otherpage.html") aren’t working.

<!DOCTYPE html>
<head>
    <script src="javascript/srcipt.js"></script>
</head>
<html>
    <form name="form" onsubmit="Distance();" method="POST">
        <p>
            <label for="dLondon">Distance from London</label>
            <input type="number" id="dLondon" name="dLondon" min="0" required>
            <label for="dLondon">miles</label>
        </p>
        <p>
            <label for="dCanberra">Distance from Canberra</label>
            <input type="number" id="dCanberra" name="dCanberra" min="0" required>
            <label for="dCanberra">miles</label>
        </p>        
        <p>
            <label for="dOttawa">Distance from Ottawa</label>
            <input type="number" id="dOttawa" name="dOttawa" min="0" required>
            <label for="dOttawa">miles</label>
        </p>
        <input type="submit" value="Submit">
    </form>
</html>
function Distance() {
    let dLondon = document.forms["form"]["dLondon"].value;
    let dOttawa = document.forms["form"]["dOttawa"].value;
    let dCanberra = document.forms["form"]["dCanberra"].value;
    if ((3900 <= dLondon) && ( dLondon <= 5200)) {
        if ((5500 <= dCanberra) && (dCanberra <= 6700)) {
            if ((6700 <= dOttawa) && (dOttawa <= 9300)) {
                location.href = "otherpage.html";
            }
            else {
                alert("Ottawa Distance isn't correct !");
            }
        }
        else {
            alert("Canberra distance isn't correct !");
        }
    }
    else {
alert("London Distance isn't correct ! ");
}
}

location.href = "otherpage.html"; or location.replace("otherpage.html") Aren’t working, and adding window. infront isn’t changing anything.

Is it secure to export variables from the main.js file?

I’ve been looking for a way to share/reference variables from my main.js to a router file. I came across this question and tried sharing the variable over the locals of the app, which did work, but it required to get the variable from the locals for each route. So I thought I might just export the variables I need and import them in the router file, which also works, but makes me worried that the variables are exposed.
It looks like this:

main.js

//imports
const APP = express();
const httpServer = createServer(APP);
export const io = new Server(httpServer);

// APP configuration

export const sessionStore = new MySQLStoreInstance(storeOptions);
...

router.js

import {io, sessionStore} from "../main.js";
...

Is it secure to share variables this way, or are they exposed in some way? If it’s not secure, how can I securely share variables between files?

Showing only previous output

I recently starting javascript.iam facing a problem whenever I run my javascript code in vs code it’s showing only previous output.

No matter how many times I change my code it still showing previous code

I try even delete my vs code completely re install it again re install node js but my problem doesn’t solve

Can I override the on – change – trigger of a selectize input?

I have a selectize input and want to change its behaviour. I normally use selectize inputs from within some framework (shiny), so I hope the example that I give here is understandable and precise.

I want to change the logic, when an onChange – event is triggered. I only want this to happen when there is one element selected, not when none is selected. In case the user deletes the element and leaves the form untouched, I want to restore the value that was active before.

Have a look at the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selectize Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/css/selectize.default.min.css">
</head>
<body>

<select id="select-beast" multiple placeholder="Select a beast...">
  <option value="lion">Lion</option>
  <option value="tiger">Tiger</option>
  <option value="bear">Bear</option>
  <option value="elephant">Elephant</option>
  <option value="rhino">Rhino</option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/js/standalone/selectize.min.js"></script>

<script>
$(document).ready(function() {
  var selectize = $('#select-beast').selectize({
    delimiter: ',',
    persist: false,
    create: function(input) {
      return {
        value: input,
        text: input
      }
    }
  });

  selectize[0].selectize.on('change', function() {
    var value = selectize[0].selectize.getValue();
    console.log(value);
  });
});
</script>

</body>
</html>

So in my case the log message should only ever print out something like Array["bear"] but never an empty array. I know that in this case one could do a if before the console.log but I am explicitly asking for changing the onChange condition because in my real problem I have no direct control on what my framework is doing. Is there a way of achieving my goal?

  • no change-event with empty selection
  • restoring the value that was there before, once the user gives focus to another element

I would claim that it is pretty natural to want something like that, so maybe there is even a plugin capable of achieving my goals?

React state array showing a length of 0 in for loop

I’m trying to create a component on my site that shows “Similar items” a user may want to see. When I pull in this component, I pass an array through search

ex. search = [‘bmw’, ‘suspension’, ‘springs’]

I set a limit of how many results I want (ex. 5) and then have the component grab listings based on each tag starting with the first. If BMW only returns 2 items, then it should search for suspension and limit it’s return count to 3 until the limit of 5 listings has been met. In the for loop, I’m trying to track how many listings have already been pulled and adjust the query limit accordingly but I always get a length of 0 in the loop. See console log below.

import { useEffect, useState } from 'react'
import ListingTile from '@components/listing/ListingTile';

const ListingGrid = ({search, activeItem, limit = 5}) => {
    const [listings, setListings] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchListing();
    }, [search])

    const fetchListing = async () => {
        //set search array has been passed
        if (search.length > 0) {
            for(let i = 0; i < search.length; i++) {

                //stop searching for similar items if limit has been reached.
                if(listings.length === limit){
                    break;
                }

                console.log(listings.length) //ALWAYS RETURNS 0

                //limit results to limit - the items already in the listing state. 
                const response = await fetch('/api/listing?limit=' + parseInt(limit-listings.length) + '&search=' + search[i]);
                let data = await response.json();
        

                //don't show the current item user is viewing if returned in results
                if(activeItem && data.listings){
                    data.listings = data.listings.filter((item) => {
                        return item._id !== activeItem
                    })
                }

                //push listings to state and continue till limit has been reached
                setListings([...listings, ...data.listings]);
            }
        }

        setLoading(false);
    }

    return (
        <>
            {loading ? (
                <div className="grid-container grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-6">
                    <div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
                    <div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
                    <div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
                    <div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
                </div>
            ) : (
                <div className='grid-container grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-6 mb-6'>
                    {(listings.length > 0) && listings?.map((listing) => (
                        <ListingTile key={listing._id} listing={listing} />
                    ))}
                </div>
            )}
        </>
    )
}

export default ListingGrid

Single object not generating array in wso2

I want to transfrom the xml to json while an element “Coll” in the incoming xml will be an array if single object received. Result.Coll needs to be an array object rest will be same.

<Result xmlns="http://ws.apache.org/ns/synapse">
  <ban:DOB xmlns:ban="http://TCS.BANCS.Adapter/BANCSSchema">22101991</ban:DOB>
  <ban:TDNPFlag xmlns:ban="http://TCS.BANCS.Adapter/BANCSSchema">N</ban:TDNPFlag>
  <ban:DNPExpryDt xmlns:ban="http://TCS.BANCS.Adapter/BANCSSchema"/>
  <ban:NibbsBVN xmlns:ban="http://TCS.BANCS.Adapter/BANCSSchema"/>
  <ban:Fac xmlns:ban="http://TCS.BANCS.Adapter/BANCSSchema"/>
  <ban:Coll xmlns:ban="http://TCS.BANCS.Adapter/BANCSSchema">
    <ban:AcctNum>10205781559</ban:AcctNum>
    <ban:Stat>DISC</ban:Stat>
    <ban:ChqbkFlag/>
    <ban:CardFlag/>
  </ban:Coll>
</Result>

Result for above

 {"Result":{"CustNum":"00000002010784868","CustTyp":"01","RelnshpMgr":"0","Title":"1","Name":"Mr Tebogo Sekalaba","Addr1":"Botswana","Addr2":"","Addr3":"","Addr4":"","PstCode":"","HomePhnNum":"","FaxNum":"","CountryOfRes":"BW","BussPhnNum":"","MobileNum":"71961292","Natlty":"BW","NumOfChqbk":"00","NumOfCard":"00","FacltyCnt":"0000","CustLmt":"0.00","TtlBal":"-601.40","CurCode1":"BWP","ResInd":"","UsrName":"NO TELLER NAME","StmtFreq":"H","StmtCyc":"00","StmtDay":"31","GrpCode":"","AvgEodBal":"0.00","FatherName":"","BlackLstInd":"N","EmplInd":"","BlackLstStat":"0","BlackLstComnt":"","CreditRtng":"0","CustStat":"0","IdNum":"652311945","VipStat":"0","AccumCnt1":"0","AccumCnt2":"0","AccumCnt3":"0","AccumCnt4":"0","AccumCnt5":"0","AccumCnt6":"0","AccumCnt7":"0","AccumCnt8":"0","AccumCnt9":"0","AccumCnt10":"0","EmailAdd":"","LagCode":"1","BrchCode":"35","RtnMailInd":"N","HldMail":"","Typ":"","VipTyp":"","name1":"Mr","name2":"","CreateDt":"19092023","MemShpLnth":"124 YEARS  003 MONTHS","CurrAge":"032 YEARS  004 MONTHS","ServLnth":"","RemainServ":"","AvailChnl1":"","AvailChnl2":"","AvailChnl3":"","AvailChnl4":"","AvailChnl5":"","AvailChnl6":"","AvailChnl7":"","AvailChnl8":"","BioEnrollDt":"99999999","BioEnrollTime":"00:00:00","KYCFlag":"H","IdTyp":"0001","DOB":"22101991","TDNPFlag":"N","DNPExpryDt":"","NibbsBVN":"","Fac":"","Coll":{"AcctNum":"10205781559","Stat":"DISC","ChqbkFlag":"","CardFlag":"","AcctFlagTyp":"L","ProdDescptn":"MoMo Instant Loan","CurCode2":"BWP","RelnshpWtAcct":"OWN","Bal":"601.40","OvrdrftAcctLmt":"500.00","AcctTyp":"5000","AcctSubTyp":"0555","ShrtName":"","InstNum":"002","TagStat":"","LonOdAmt":"500.00","ArrAcctAmt":"560.00","Dpd":"2","OdInd":"","HowLong":"0.46","IBAN":"","AcctBrch":"35","CreationDt":"19092023","Acctstat":"40","PurpCod":"27","SignMndt":"","SignDetail":"","SignatoryNum":"0"}}}

Expected output

 {"Result":{"CustNum":"00000002010784868","CustTyp":"01","RelnshpMgr":"0","Title":"1","Name":"Mr Tebogo Sekalaba","Addr1":"Botswana","Addr2":"","Addr3":"","Addr4":"","PstCode":"","HomePhnNum":"","FaxNum":"","CountryOfRes":"BW","BussPhnNum":"","MobileNum":"71961292","Natlty":"BW","NumOfChqbk":"00","NumOfCard":"00","FacltyCnt":"0000","CustLmt":"0.00","TtlBal":"-601.40","CurCode1":"BWP","ResInd":"","UsrName":"NO TELLER NAME","StmtFreq":"H","StmtCyc":"00","StmtDay":"31","GrpCode":"","AvgEodBal":"0.00","FatherName":"","BlackLstInd":"N","EmplInd":"","BlackLstStat":"0","BlackLstComnt":"","CreditRtng":"0","CustStat":"0","IdNum":"652311945","VipStat":"0","AccumCnt1":"0","AccumCnt2":"0","AccumCnt3":"0","AccumCnt4":"0","AccumCnt5":"0","AccumCnt6":"0","AccumCnt7":"0","AccumCnt8":"0","AccumCnt9":"0","AccumCnt10":"0","EmailAdd":"","LagCode":"1","BrchCode":"35","RtnMailInd":"N","HldMail":"","Typ":"","VipTyp":"","name1":"Mr","name2":"","CreateDt":"19092023","MemShpLnth":"124 YEARS  003 MONTHS","CurrAge":"032 YEARS  004 MONTHS","ServLnth":"","RemainServ":"","AvailChnl1":"","AvailChnl2":"","AvailChnl3":"","AvailChnl4":"","AvailChnl5":"","AvailChnl6":"","AvailChnl7":"","AvailChnl8":"","BioEnrollDt":"99999999","BioEnrollTime":"00:00:00","KYCFlag":"H","IdTyp":"0001","DOB":"22101991","TDNPFlag":"N","DNPExpryDt":"","NibbsBVN":"","Fac":"","Coll":[{"AcctNum":"10205781559","Stat":"DISC","ChqbkFlag":"","CardFlag":"","AcctFlagTyp":"L","ProdDescptn":"MoMo Instant Loan","CurCode2":"BWP","RelnshpWtAcct":"OWN","Bal":"601.40","OvrdrftAcctLmt":"500.00","AcctTyp":"5000","AcctSubTyp":"0555","ShrtName":"","InstNum":"002","TagStat":"","LonOdAmt":"500.00","ArrAcctAmt":"560.00","Dpd":"2","OdInd":"","HowLong":"0.46","IBAN":"","AcctBrch":"35","CreationDt":"19092023","Acctstat":"40","PurpCod":"27","SignMndt":"","SignDetail":"","SignatoryNum":"0"}]}}

I have tried using and javascript to make single object array and respond json but doesnot works.

How do I achieve the expected output?

Formulário de e-mail e Google API

Eu estou com um problema e não consigo solucionar, criei um código em JS para enviar e-mails via Google API, e tbm criei um formulário HTML para receber o e-mail do usuário. Eu preciso conectar esse e-mail recebido do formulário ao parâmetro To: do código da API do Gmail.

Alguém sabe como eu posso linkar esses dois códigos?

Eu tentei criar uma VAR para receber o e-mail e declarei ele em to: mas não funcionou, também tentei fazer uma função mas não funcionou, acredito que seja problema de lógica minha. Alguém já fez isso antes?

Get a number from a string using charCodeAt

const text = "Hello team, I checked my wallet balance, there is 0,0000341 USDT, I can not buy anything";

Need to get a number using only one loop for and charCodeAt()

const parseBalance = (str) => {
  const zero = "0".charCodeAt(0);
  const nine = "9".charCodeAt(0);
  const coma = ",".charCodeAt(0);
  let num = 0,
    factor = 1;

  for (let i = str.length - 1; i >= 0; i--) {
    const char = str.charCodeAt(i);
    if (char >= zero && char <= nine) {
      num += (char - 48) * factor;
      factor *= 10;
    }
  }
  return num;
};

Need result: 0.0000341
My result is 341
Tell me how to correct the formula for writing zeros