on load function not defined

My onload function is apparently not defined. I have been looking forever and cant figure out why. If the answer to this is quick or I am just being stupid, keep in mind, I have never taken a CSE class and this has been so hard but thought I would ask lol. enter image description here

enter image description here

enter image description here

I have attached my work in the other tab, my HTML, and the defined function that I have made and am trying to onload.

Thank u everyone 🙂 also if i may ask if anyone knows can they please explain in layman’s terms. I am horrible at this stuff lol.

compare specific values from objects with different keys Javascript

This is a silly question, but nothing I try works.
I have two objects nft and web3.givenProvider. Both contain an address as "0x0000000000000", but they are under separate keys. nft is under .seller and web3 is under .selectedAddress. Whenever I try to compare them using _.isEqual or toString it returns false even though the values are correct. I am not sure what I am missing here. I have even tried converting to an array and trying to _.find the address in the array, but that returned false.

console.log(nft.seller === web3.givenProvider?.selectedAddress))

Display coordinates value in input text after button clicked

help me with this. I have a javascript to get current user coordinates (latitude & Longitude) by using a botton. So, what I want is when clicked the button, it will get the coordinates and display in the two input text which is one for latitude and one for longitude. Before this, I just display it in <p> element.

HTML & PHP:

<div class="mb-3"><input class="border rounded-0 form-control" type="text" name="business_latitude" id="" placeholder="Latitude" style="font-family: Roboto, sans-serif;" value="<?php echo $bizLat; ?>"></div>
<div class="mb-3"><input class="border rounded-0 form-control" type="text" name="business_longitude" id="" placeholder="Longitude" style="font-family: Roboto, sans-serif;" value="<?php echo $bizLong; ?>"></div>
<p id="lati"></p>
<p id="longi"></p>

Javascript:

var x = document.getElementById("lati");
    var y = document.getElementById("longi");

    function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
    }

    function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude;
    y.innerHTML ="Longitude: " + position.coords.longitude;
    }

<?php echo $bizLat; ?>, <?php echo $bizLong; ?> here is where they get saved coordinates in database. I just want to edit the latitude and longitude by pressing the button.

how to do the update when my key is called key

I have a problem with an update in dynamoDB , when performing the update in dyanamo it tells me that I cannot use the key keyword

“message”: “Value provided in ExpressionAttributeNames unused in expressions: keys: {#keyid}”,
“code”: “ValidationException”,
“time”: “2022-05-06T00:24:03.502Z”,

When using the ExpressionAttributeNames I must relate the key with a different name “Key” but in the table its id is called key and it generates the previous error when updating this my code.

 function updateUser(key, sortkey, dateFiling) {

try {

    let params = {
        TableName: env.getEnv(CTE.User),
        Key: { "#keyid": key , "sortkey": sortkey },
        UpdateExpression: "set dateFiling = :dateFiling",
        ExpressionAttributeNames: { '#keyid': 'key' },
        ExpressionAttributeValues: { ":dateFiling": dateFiling }
    };

    await db.updateItem(params);

    console.log(params); 
}

catch (error) { 

    console.log('Error  in updateUser %j:', error);

}
}

my doubt is exactly with the ExpressionAttributeNames since it does not take the keyid envelope to refer to the key and not have a problem with the use of the reserved word. Can somebody help me. please

Trying to replicate .bind() in JavaScript

I am learning JavaScript and I am trying to replicate some of the built-in methods like .push() .indexOf() etc..

So far so good and it is helping me a lot to learn the core of JavaScript.

But I came across .bind() and I can´t figure out a way of knowing the function that is calling the .bind() and tell my new .bind2() method to use it with the new THIS from our Object.

This is what I am trying:

const human = {
  firstName:"Humano",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + "  " + this.lastName;
  }
};

const member = {
  firstName:"Member",
  lastName: "Nilsen",
};

window.prototype.bind2 = function(obj) {
        if (typeof obj !== "object" ) {throw `${obj} is not an Object, I will work hard to return undefined later on`};
        return function(){
                return obj;
        }
    };

let testBind2 = human.fullName.bind2(member);
console.log(testBind2()); // {firstName: 'Member', lastName: 'Nilsen'}

So all I could do is to return the THIS from the Object passed as an argument but I have no idea how I can grab inside the .bind2() the fullName method (or any method that we want to bind) from the object that is actually calling the method .bind2().

Once we could grab the fullName we can pass it to bind2() and tell it to use THIS from our object.

This is only for the sake of learning and it would be amazing if someone could tell me if it is possible and how.

Thank you

How do I update the value in object if the id matches?

How do I update the title in data if the id matches?

const data = {
    "0": {
        "id": 1912,
        "title": "Books",
    },
    "1": {
        "id": 1958,
        "title": "Brands",
    },
    "2": {
        "id": 2037,
        "title": "Logo",
    },
    "3": {
        "id": 2038,
        "title": "Colour",
    },
}

For example,
This is the object with the latest updated title with the id: 1912.

const updatedData = {id: 1912, title: 'The Books'}

Sample output after updating data with updatedData

const data = {
    "0": {
        "id": 1912,
        "title": "The Books",
    },
    "1": {
        "id": 1958,
        "title": "Brands",
    },
    "2": {
        "id": 2037,
        "title": "Logo",
    },
    "3": {
        "id": 2038,
        "title": "Colour",
    },
}

minimum of list to maximum of value in Javascript

I currently have a list in Javascript:

let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0]
where each value of this is a dollar coin.

My problem is the following, I need some equation for Javascript to choose the smallest possible number of coins to reach the maximum in the desired value.

I’ll give an example:

I need as few coins as possible to max out at 5.5USD. I would use a coin of 2.5USD and 3 coins of 1.0USD to arrive at 5.5USD.

What math function would I use for this?

running automatic increas value on javascript php

im trying this code in my last project is running normaly.but i make a new project with this code is not running,where im wrong?

sorry my laguage english not good

    var speed = 10;
    var balance = 100;

    function startRunning() {

      setInterval(() => {
        if (logged) {

          balance = balance + (speed / 10);
          $("#running").text((balance).toFixed(8))

        }


      }, 100);

    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="running">100</span>

What are the use case of self-calling function? [duplicate]

Self-calling function is a function that executes automatically when you create it, and has the following form:

(function(){
    // some private code that will be executed automatically
})();  
(function(a,b){
    var result = a+b;
    return result;
})(10,20)

What I am curious about this is why we need this? Thus these functions don’t have their own names, developers won’t be able to call them anywhere they want which causes poor code reuse.

react native possible uhandled promise rejection

im getting the following errors
Possible Unhandled Promise Rejection (id: 0):
TypeError: user.slice is not a function. (In ‘user.slice()’, ‘user.slice’ is undefined)

I need the code to be able to pass the data too return the list of users in order of most matching elements to least. I was able to get the function working in replit with a made up data base once I try to put it in my project I am getting trouble, please help.

 auth().onAuthStateChanged(user => {
          if (user) {
            // User is signed in, see docs for a list of available properties
            // https://firebase.google.com/docs/reference/js/firebase.User
            const profile = getUserProfile(user.uid);
            profile.then(pro => {
              const addy = pro.Address;
              setAddress(pro.Address);


              const filterdUsers = FBusers.filter(user => {
                if(user.Address === addy && user.uid !== p  pro.uid){
                  
                    const items = new Set(pro)
                    
                    const rank = arr => arr.filter(user => items.has(user)).length
                    
                    return (a, b) => rank(b.items) - rank(a.items)
              
                  
                }
                  const sorted = user.slice().sort(filterdUsers(pro))
                  
                  console.log(sorted.map(user => user.items.join(', ')))
                }
              )}};
              // sort users
              //setUsers(sortByMatch);
              //vvv delete me vvv
              setUsers(filterdUsers);

Function that tests if React PWA is online never returns false

I’m using ReactJS to create a progressive web app. My app needs to determine if it is able to connect to my server so that it can know how to handle submitted data. To do this, I’m trying to write a function that returns true if and only if a HEAD request to my server succeeds.

I’m using Chrome on desktop to test my app and my server is hosted on my desktop through localhost. To test my function, I’ve created a temporary button on my app that runs the function when I click it. I then try different combinations of network throttling settings on Chrome devtools and manually connecting & disconnecting my server. I’m expecting a positive output only when my server is connected and there is no network throttling. However, I never receive a negative output.

I don’t know for sure if my methods of testing are the way to go and I’m also unsure if my approach in solving this problem is the right one. I’m open to other solutions and/or testing methods. Any thoughts?

Here is my code for my function:

const isOnline = async () => {
  if (!window.navigator.onLine) return false;

  // I use the origin to prevent CORS errors
  const url = new URL(window.location.origin);

  // Set a random search parameter to make sure no request falls back on the cache
  url.search = new URLSearchParams({
    isonline: createId(), // Returns a random string of a certain length
  });

  try {
    // HEAD request is sufficient for my needs
    const response = await axios.head(url.toString());
    console.log(response);

    // Return true if the request was valid
    if (response.status >= 200 && response.status <= 299) return true;
    else return false;
  } catch {
    return false;
  }
};

Here is my code for my button’s event handler:

const onClickIsOnline = () => {
    isOnline() ? console.log('Online!') : console.log('Offline :(');
  };

What is the best way to call a function and render a child component onClick in React?

I have the below code, I want to call a function and render a child component onCLick. What is the best way to achieve this?

import AddOrder from './AddOrder'

return (
<Button onClick={handleCheckout}>Checkout</Button>
)

const handleCheckout = () => {
        <AddOrder />
        fetch("http://localhost:5000/create-checkout-session", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                items: data?.getUser ? data.getUser.cart : cart,
                email: currentUser ? currentUser.email : undefined,
            }),
        })
            .then(async (res) => {
                if (res.ok) return res.json();
                const json = await res.json();
                return await Promise.reject(json);
            })
            .then(({ url }) => {
                window.location = url;
            })
            .catch((e) => {
                console.error(e.error);
            });
    };

I tried making a new function called handleAll and adding it like this:

function handleAll(){
   handleCheckout()
   <AddOrder />
}

AddOrder.js:

function AddOrder() {
  const d = new Date();
  let text = d.toString();
  const { currentUser } = useContext(AuthContext);
  
  const { data, loading, error } = useQuery(queries.GET_USER_BY_ID, {
    fetchPolicy: "cache-and-network",
    variables: {
        id: currentUser.uid
    },
});
const [addOrder] = useMutation(queries.ADD_ORDER); 
useEffect(() => {
    console.log('hi')
})
if(error) {
    return <h1> error</h1>;
   }
   
if(loading) {
    return <h1> loading</h1>;
   }
if (data){
let newCart = []
for(let i=0; i< data.getUser.cart.length; i++){
    newCart.push({quantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id})
}
console.log(newCart)
  addOrder({
    variables: {
        userId: currentUser.uid, status: 'ordered', createdAt: text, products: newCart
    }
  });
  console.log("hello")
}
}
export default AddOrder;

This did not work either. When I reload this it add 3 copies of the same order to the mongodb collection. What is the right way to do this?

URL redirect after using Campaign Monitor API

I am embedding a signup from provided by Campaign Monitors API. My objective is after the user submits the information (name and email) it will redirect them to a another URL (random-url.com for example)

Campaign monitor provides raw form html to embed on your site which I can easily add an onclick=”window.location.href” but in order for the user to get added to the email form is they have complete a captcha which isn’t visible on the raw form html.

If I add an onclick to the button it re-directs them right away and doesn’t complete the capthca which actually sign them up to the form. Explaining this best as I could

  1. Is there a way to call onclick function after Campaign monitors JS has completed?

                     <form class="js-cm-form" id="subForm" class="js-cm-form"
                 action="https://www.createsend.com/t/subscribeerror?description=" method="post"
                 data-id="2BE4EF332AA2E32596E38B640E90561910B888CEF1E0E5207BA8D9A159670EA3D79956DF2A17D1C977FA3FC98C11A551DE4FFED9A655155C23CD1E7F633CDDCA">
                 <div size="base" class="sc-jzJRlG bMslyb">
                 <div size="small" class="sc-jzJRlG liOVdz">
                 <div><label size="0.875rem" color="#5d5d65" class="sc-gzVnrw dEVaGV">Name <span
                 class="sc-dnqmqq iFTUZ">*</span></label><input aria-label="Name"
                 id="fieldName" maxLength="200" name="cm-name" placeholder="Your name" required
                 class="sc-iwsKbI iMsgpL" /></div>
                 </div>
                 <div size="small" class="sc-jzJRlG liOVdz">
                 <div><label size="0.875rem" color="#5d5d65" class="sc-gzVnrw dEVaGV">Email <span
                 class="sc-dnqmqq iFTUZ">*</span></label><input autoComplete="Email"
                 aria-label="Email" id="fieldEmail" maxLength="200" name="cm-jjkthut-jjkthut"
                 placeholder="Your Email" required type="email"
                 class="js-cm-email-input qa-input-email sc-iwsKbI iMsgpL" /></div>
                 </div>
                 <div size="base" class="sc-jzJRlG bMslyb"></div>
                 </div><button size="1rem" color="#fff" type="submit"
                 class="js-cm-submit-button sc-iAyFgw czcIUB">Start Waiver
                 </button>
                 </form>