For event.target in onclick – “Uncaught TypeError TypeError: Cannot set properties of undefined (setting ‘value’)”

I’m trying to have my html call a javascript function onclick in which the function itself references the event that called it, but I keep getting this error:

Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')
    at play (c:UsersC2RanDesktopPracticeapp.js:5:16)
    at onclick (c:UsersC2RanDesktopPracticeindex.html:24:68)

Here’s my html:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="app.js" defer></script>
</head> 
<body>
    <input type="button" value="X" id="turn" onclick="play(this);">
</body>
</html>

Here’s my javascript:

var turn = "X"

function play(event) {
    var cell = event.target;
    cell.value = turn;
    console.log(turn);
    if(turn == "X")
    {
        turn = "O"
    }
    else 
    {
        turn = "X"
    }
}

Is there something I’m missing? Why is it saying value is undefined? Is it not getting the event correctly? Or does onclick not count as an event? I also tried event.currentTarget instead

Where to start with a simple banking app? [closed]

I’m working through a course on JavaScript currently and honestly I’m having a pretty difficult time with it. If anyone has any resources they could recommend for learning, I’d appreciate it!

I’m trying to make a simple banking app with these requirements:

  • The user should see a prompt so they can type which action to perform.

  • The user will have a list of 4 actions to choose from.

  • Enter Q to quit (immediately quits the program).

  • Enter W to withdraw.

    • The user will be prompted again to enter an amount to withdraw. After withdrawing money,
      they should be able to type another option.
  • Enter D to deposit.

    • The user will be prompted again to enter an amount to deposit. After depositing money,
      they should be able to type another option.
  • Enter B to view balance.

    • The user will see their balance. Afterwards, they should be able to type another option.
  • The balance should update after any Withdrawal or Deposit transactions.

  • The program will loop asking for input until the user enters Q.

Here’s my basic HTML for a very simple site

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Welcome!</h1>
    <button onclick="start()">Click here to get started.</button>
    <script src="scripts.js"></script>
  </body>
</html>

And here’s as far as I’ve been able to get with the JS…

function start() {
  let input = prompt('What would you like to do?');

  if input = 'w' {
    alert('Withdraw');
  } else () {

  }
}

And I know that’s probably not even the direction I need to be going. I’m honestly stuck because I don’t really know where to start. Any and all advice is much appreciated, TIA!!

is there any way to save the value of onChange?

I’m having a question about onChange, so I was trying to pick up and send a value from my onChange to (”http://localhost:3000/search”), but when I press the (Enter) key it enters the page but ends up deleting the values of my onChange coming back undefined, is there any way to save my onChange and send to another page? without retone me undefined

My code:

function handleKeyPress(event: any) {
        if(event.keyCode === 13){
          open('http://localhost:3000/search')
        }
      }

    function search(e: any) {
    
        axios.get("http://localhost:3001/search", {params: {q: e.target.value}})
    
    }
    
    return(
        <>
            <div className={styles.Header}>

                <input name='q' type="text" placeholder='Buscar' onChange={(e)=>search(e)} onKeyDown={(e)=>handleKeyPress(e)}/>

                <div></div>
            </div>
        </>
    )

How do I efficiently create this multi button sound program in p5js

I’m trying to create a binaural audio sound demo player in p5js. It basically plays different sounds close, far, up, down, right, left, as if you were in a room. I’m new to p5js and have been struggling to create 8 circular buttons, arranged in a circle, that all play and pause various sounds. These buttons should change color and I am not sure why I’m having so much trouble but help is appreciated. The issue I’m having, so other people can be helped too, is how do I create multiple object buttons that change color and coordinate sound and text with each one? I tried using an array and constructor but it didn’t work. Thank you 🙂

https://editor.p5js.org/sheepblazer/sketches/TbRI7EmAH

I just attached the link to my editor as I thought it would be easier.

alternate depending on whether their id is odd or even React

I am using React for a web page. In a component, I have a div on the left and an image on the right.

I would like them to alternate depending on whether their id is odd or even.

function Item({ title, text, link, img,id }) {
  return (
    <div >
      <div>
        <h3>
          {title}
        </h3>
        <p>{text}</p>
        <a href={link}>
          text
        </a>
      </div>
      <img src={img} alt={title} />
    </div>
  );
}

How to close popup.html for my google extension?

How can I visibly hide my popup.html whenever I click a button on that popup. I want to keep my scripts running but minimize the popup off the page. The reason i’m doing this is because i’m making an eye dropper extension that can get the color under your cursor and perhaps that color is being blocked by the popup hence why I want to get hide it when I’m looking for a color. Once I’ve picked my color the popup reappears.

how to query from firebase realtime database with security rules applied

I have setup a basic security rules of firebase realtime database for this question. Before I jump to the problem, I have created a Flutter mobile app with GetX and also I have installed http: ^0.13.4 plugin for querying.

Here is how I set the security rules

{
  "rules":{
    ".read" : "auth.uid !== null && auth.token.email_verified == true",
    ".write" : "auth.uid !== null"    
  }
}

So basically, I want users to be able to read the data if they are authenticated and email verified.

And for write rule, only if the user is authenticated and the custom claims of isAdmin is set to true. For isAdmin, I don’t know to set it in the security rules.

Is it something like this?

"auth.uid !== null && root.child('isAdmin').val() == true" 

Anyways, my problem is how to query using http plugin on client side?
Here is a sample of GET query

Uri url = Uri.parse('URL HERE with /.json file');

getIPTIdAndName() async {
  iptList.value = [];
  await http.get(url, headers: {"Authorization": FirebaseAuth.instance.currentUser!.uid}).then(
    (value) {
      var response = json.decode(value.body) as List<dynamic>;
      for (var i = 0; i < response.length; i++) {
        iptList.add({
          "iptIndex": i,
          "iptId": response[i]['id'],
          "iptName": response[i]['name']
        });
      }
      iptList.refresh();
    },
  );
}

How to query if the security rules is set?

POST returns undefined with Cloud Function

I’m implementing Stripe for React Native and I’m trying to send the customerId to my Cloud Function using POST, but when I execute the code it returns in the console.log undefined

Cloud Function (Firebase)

exports.addCardForExistingCustomer = functions.https.onRequest(async (request, response) => {

   let id = await request.body.customer_id
  
   response.send({
     result: id
   })
});

Client side

const fetchPaymentSheetParams = async () => {
    const response = await fetch(`${API_URL}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ customer_id: customerId })
    });
    const { result } = await response.json();

    console.log(result)

  };

Equal sides of an array in JS

Question: Take an array with integers and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. Let’s say you are given the array {1,2,3,4,3,2,1}:
Your function equalsides() will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.

I have written the following

  1. Declare two variables mid and i where
    mid the index we are looking for
    i= this is starting index
  2. Then while (mid<= arr.length-1) we will go through the array and add up each side of the array one side from i=0 to i=mid and then from i=mid to i=array.length-1, while adding up each side to leftSum and rightSum respectively
  3. And if leftSum==rightSum in any of these instances we will return mid if it didnt it will increase mid by one and reiterate ,
  4. If mid is not returned we will return -1 at the end.

In code it is the following

function findEvenIndex(arr)
{
  //Code goes here!
  let mid =1;
  let leftSum=0;
  let rightSum=0;
  while(mid<(arr.length-1)){
   
      
    for(i=0;i<mid;i++){
      
        leftSum=leftSum+arr[i]
      
    }
    
    rightSum = rightSum + arr[mid]
 
 
    if(rightSum==leftSum){
        console.log("mid: "+ mid);
        return mid;
    }
    else{
        
        mid++;
        
    }

  }
 return -1;
}

however I am not sure why this is not working, any help would be appreciated

H88 Error: Invalid account: #0 for network: mumbai – Expected string, received undefined

This is my hardhat.config.js file code


module.exports = {
  solidity: "0.8.4",
  networks: {
    hardhat: {
      chainId: 1337
    },
    mumbai: {
      url: "https://rpc-mumbai.matic.today",
      accounts: [process.env.pk]
    },
    // polygon: {
    //   url: "https://polygon-rpc.com/",
    //   accounts: [process.env.pk]
    // }
  }
};

When running npx hardhat test the following error appears:

**Error HH8: There’s one or more errors in your config file:

  • Invalid account: #0 for network: mumbai – Expected string, received undefined**

Seems I have a couple of errors with my hardhat.config.js file but can’t locate. I am using Nader Dabit’s full-stack-web3 tutorial for full stack web3 development.

Load and access data sequentially within functions in a JavaScript class

I need to load data from json into a function within a class. The data loads but the sequence is off as shown below. How can I get the data 1st before the process continues?

”’

"use strict";

customElements.define('myexample', class extends HTMLElement {
    constructor() { 
        super();
        …
    }

    connectedCallback() {
         ….
         this.paths = [];
         let go=this;
         go.loaditems ();
    }


    loaditems(){
        …
        this.getimage();
    }

    //problem area: data is 
     getimage(){
        …
        this.pic=[]
        let retpic= this.processpic();
        alert(“returned in place: “ + retpic”);
        this.pic=retpic;
         … (other processes that require reference with “.this”)
    }
    alert(“after returned pic”);
    
    processpic(){
            $.get("pics.json", function(data){
                let ds = data.pics[0].pic1 + “.jpg”;
                return ds;
            })
    }

});

”’

Problem: the alert(“after returned pic”) fires before the image is loaded. Putting a callback with processpic() and wrapping getimage() within the callback makes it impossible to properly reference “this.”

How can I get all the different values for the same key in an array (JS)?

I’ve an array Like:

var array = [
            {charId: 'REFPER', text: 'Reference Period', selectOpt: 'EQ'}, 
            {charId: 'REFPER', text: 'Reference Period', selectOpt: 'EQ'},
            {charId: 'OTXDAY', text: 'Older Than x Days', selectOpt: 'EQ'},
            {charId: 'REFPER', text: 'Reference Period', selectOpt: 'EQ'},
            {charId: 'OTXDAY', text: 'Older Than x Days', selectOpt: 'BT'}
            ];
            
How I can achieve:

var newArray = [{
                param: 'REFPER',
                value: [{text: 'Reference Period',
                        selectOpt: 'EQ'
                        },
                        {text: 'Reference Period',
                        selectOpt: 'EQ'
                        },
                        {text: 'Reference Period',
                        selectOpt: 'EQ'
                        }]
                },
                {
                param: 'OTXDAY',
                value: [{text: 'Older Than x Days',
                        selectOpt: 'EQ'
                        },
                        {text: 'Older Than x Days',
                        selectOpt: 'BT'
                        }]
                }];

I need to save it in database.
I viewed: How to add an object to an array
JavaScript: Push into an Array inside an Object?
Thanks in advance.

How to permanent change html text after a submitted has been triggered

Im currently trying to find out if its possible to change a text in extension when a submit has happend. I currently have a text saying “ENTER DISCORD USER ID AND SUBMIT” and when an user has entered its USER ID and submitted, the text should be changed to “USER ID SUBMITTED” and the text should always say that afterwards, meaning that if someone closes and opens the extensions – the text should still say “USER ID SUBMITTED”.

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="../css/style.css">
    <script src="../js/popup.js"></script>
</head>

<body>
    <div class="text-center">
        <form id="form" class="form-control mt10">
            <label> <input type="number" id="discord-id-input" name="discord-id-input"></label>
            <button id="discord-id-button" type="submit" class="submit"></button>
            <output id="help-text" class="help-text" value="">ENTER DISCORD USER ID AND SUBMIT</output>
        </form>
    </div>
</body>
function get_discord_id(callback) {
    chrome.storage.sync.get(["discord_id"], (result) => {
        callback(result.discord_id);
    });
}

function set_discord_id(discord_id) {
    chrome.storage.sync.set({ discord_id: discord_id }, () => {});
}

window.addEventListener("DOMContentLoaded", (e) => {
    // check if discord ID is already stored
    get_discord_id((discord_id) => {
        if (discord_id == null) {
            form.addEventListener('submit', () => {
                let value = document.getElementById("discord-id-input").value;

                chrome.runtime.sendMessage({ discord_id: value }, function(response) {});

                set_discord_id(value);
                document.getElementById('help-text').innerHTML = 'USER ID SUBMITTED';
            });
            e.preventDefault();
        };
    });
});

I wonder how I am able to permanent change a text after a submitted trigger has happend?

Firestore realtime updates missed while disconnected

I have a simple web app that uses Firestore to receive realtime updates. For simplicity, I can demonstrate the issue with the example from the documentation:

const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => {
  console.log("Current data: ", doc.data());
});

I am NOT using offline persistence and am using v 9.6.8.

Under normal conditions, everything works as expected. When I lose connectivity, however, I am not notified of changes that happen while disconnected even after connectivity is restored (I simulate this by going on ‘airplane mode’).

One option I’ve considered, but not yet tried, is to subscribe to connectivity events from the device (online and offline windows events). Before pursuing this option, I was wondering if there is a simpler or better solution.

How to add Google Ads conversion purchase event to my WooCommerce Thank you Page

I saw this
Adding Google Ads Event Snippet To Conversion Page (thank you.php)

But I have a different situation. I am using ” Auto Complete Processing WooCommerce orders on Thank you Page” and “Redirect WooCommerce checkout page” all these are inside my functions.php file.

This is what my functions.php file looks like. I hid my site with ” ********* “

//Auto Complete Processing WooCommerce orders on Thankyou Page

add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    if ( $order->has_status('processing') ) {
        $order->update_status( 'completed' );
    }
   
}

// Redirect WooCommerce checkout page to ******************** after the payament
add_action( 'woocommerce_thankyou', 'pfwp_redirect_woo_checkout');
function pfwp_redirect_woo_checkout( $order_id ){
    $order = wc_get_order( $order_id );
    $url = 'https://*********/*********/*********/';
    if ( ! $order->has_status( 'failed' ) ) {
        wp_safe_redirect( $url );
        exit;
    }
}

And I want to add the Event snippet inside the Thank You for google ads.

<!-- Event snippet for Purchase conversion page -->
<script>
  gtag('event', 'conversion', {
      'send_to': 'AW-***********/********kDENy8vL4o',
      'value': 1.0,
      'currency': 'SAR',
      'transaction_id': ''
  });
</script>
<!-- End Event snippet for Purchase conversion page -->


Because I am redirecting the thank you page to another page, the script will trigger? Or not?

And how and where do I add the Event snippet at the functions.php because I have a lot of code that control WooCommerce?