Adding a form in html using javascript

I am trying to configure on how to add a form whenever you click the add button. Can someone help me with this? I attached a jsfiddle so that you can fully understand what I am saying

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div style="display: none;" id = "form1">
                  
  <form action="" method="" id = "add-order-form">
  <div class="row add-order-info text-center">
    <div class="col"> 
      <div class="dropdown">
        <button type="button" class="btn dropdown-toggle" 
        data-bs-toggle="<dropdown">
        Select...
        </button>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Mouse</a></li>
            <li><a class="dropdown-item" href="#">Monitor</a></li> 
            <li><a class="dropdown-item" href="#">Keyboard</a></li>
          </ul>
        </div>
      </div>
   </div>
   </form>
</div>
<button type="button" value ="Add Child" onclick="addForm();" id = "add-button">
Add
</button>
                

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
 function addForm() {
        document.getElementById('form1').style.display = 'block';
        
        
        $("#add-order-form").clone().appendTo("#form1");
       
        }

https://jsfiddle.net/u0pzeqry/1/

Using Jest with NodeJS, Function in imported module not being mocked without using ‘this’ in main

In the setup below, if I run the test as is, myFunc is not mocked when I debug into handler.

However, if instead I add this. in front of the myFunc call in handler, then the function is mocked and everything works as expected.

Can someone please explain why this is? I’m new to mocking and can’t see it.

I know what this does, but why won’t jest mock without it since I told it to mock that function in the module?

index.js

const aws = require('aws-sdk')

  exports.handler = async function (event, context) {
  
    let s;
    switch (event.func) {
      case "myFunc":
        console.log('Executing shouldProceed');
        //making the call: s = await this.myFunc.apply(null, [event.params]) will make the mock work.
        s = await myFunc.apply(null, [event.params]) 
        console.log(s);
        return s;
      /*cases...*/
      default:
      // default behaviour
    }

    async myFunc({p1, p2}){
        /* do something */
        return x
    }
    exports.myFunc = myFunc
  }      

index.spec.js


jest.mock('./index.js', () => {

    const allAutoMocked = jest.createMockFromModule('./index.js')
 
    const actual = jest.requireActual('./index.js')
  
    return {
      __esModules: true,
  
      ...allAutoMocked,
  
      myFunc : jest.fn().mockImplementation(() => ({ mockedValue: 'test' })),
  
      handler: actual.handler
    }
  })

let index = require("./index.js")

describe('Test myFunc', () => {
        
    test('If myFunc function was called', async () => {
        var event = { func: 'myFunc', params: { p1: xx, p2: false } };
        const context = {};
        const logMock = jest.fn((...args) => console.log(...args));

        const data = await handler(event, context);
    })
})


SQL query with multiple optional query parameters

I’m using Amazon RDS to store and query data and I want to implement a searching feature by 3 query string parameters which should be optional. I need to add this query to the existing one. Now I have something like this:

    const { id } = event.pathParameters;
    const { date_from: dateFrom, date_to: dateTo } = event.queryStringParameters;
    const page = event.queryStringParameters.page || "0";
    const size = event.queryStringParameters.size || "10";
    const orderBy = event.queryStringParameters.orderBy || "date";
    const direction = event.queryStringParameters.direction || "DESC";
    const firstName = event.queryStringParameters.firstName || null;
    const lastName = event.queryStringParameters.lastName || null;
    const email = event.queryStringParameters.email || null;

    const q = `SELECT * FROM "my_table".test t where t.id='${id}' 
        AND t.date >= '${dateFrom}' AND t.date < '${dateTo}' 
        AND t.result IS NOT NULL
        ORDER BY ${orderBy} ${direction}
        LIMIT ${size} OFFSET ${page * size}`;

I want to search the table by firstName, lastName, or email in case they are provided in query string parameters and to add that part of the query to the existing one.

What would be the cleanest and most efficient way to implement that?

Thanks!

LOADING copy appears not translated

Often in StandAlone the black copy with label “Loading” is shown for few seconds before to show BIPA;

In Embedded it is rare to happen.

STR

Go to any banner

Select any lang (but no EN)

select upc with VM

Open VM in Embedded or STand ALone

ACTUAL

the Label is not translated basic the previously lang app selected

The Label have to shown in correct language

How to load and change the default option in JavaScript?

Code

I am having a form like this in HTML:

<label for="alternativeGraph">Alternative graphs could be seen here:</label>
         <select id="selGraph" onchange="graphUpdate()" aria-label="Graph">
                <option value="1" selected="selected">Graph 1 (default)</option>
                <option value="2">Graph 2</option>
                <option value="3">Graph 3</option>
                <option value="4">Graph 4</option>
                <option value="5">Graph 5</option>
            </select>
      <button type="button" onclick="setDefault()"> Change default graph</button>

I am planning to load Graph 1 as my default option when the page is loaded, and to change my default graph with setDefault() function. Here is my JavaScript code for it:

function render(filename) {
fetch(filename).then(response  => response.text()).then(textAsString => 
     renderString(textAsString));
}

   
function graphUpdate(){
    let value = document.querySelector('#selGraph');
    let graph = ["graph_1.gv", "graph_2.gv", "graph_3.gv", "graph_4.gv", "graph_5.gv"]
    render(graph[value.selectedIndex]);
    
}

// function setDefault(){ # I am not sure about what should be added here...
//     let new_default_graph = document.querySelector("#selGraph");
//     new_default_graph.value = 
    

// }

Issues

The main problem is that when I load the website, Graph 1 (“graph_1.gv” file) is not loaded, despite of my choice as the default graph. Only when I clicked on the dropdown form did the graph show up. (Other graphs are still loaded, though).

Questions:

Are there any method that could read from my selected option and load it from the beginning? And also, what should I do with my setDefault() function so that when users choose option 3 for example, the website could save this option as the default one when being refreshed?

JS React: Two Objects, change properties if name matches

i have a problem with Objects in JavaScript (React).

I have two different Objects, which are generated from two different XML-Files. Each Object has the same Names in it but the points and position can be different. My Goal is to add the Points from the second Object to the First if the name matches.

The Structure of the Objects is the following:

let obj = [{name: "Max", points: 2},{name:"Marc", points: 1}]
let obj2 = [{name:"Marc", points: 2},{name: "Max", points: 1}]

The Goal is to have one updated Object:

let updatedObj = [{name: "Max", points:3},{name:"Marc", points:3}]

My Code looks like this rn:

import React, {useState} from 'react'
import axios from 'axios'

const App = () => {

    const [list1,setList1] = useState()
    const [list2,setList2] = useState()

    const readFile = (file, number) => {
        const dayPath = `/files/`;

        axios.post(`http://localhost:5001/getData`, {dayPath, file})
        .then(res => {
            // File Number 1
            if(number === 1){
            let obj = res.data.vehicles[1].vehicle.map((item) => (
            {
              name: item.name,
              points: res.data.vehicles[0] - Number(item.Position) +1 // Vehicles Total - Position + 1
            })
          )  
          setList(obj)
          }else {
            /* 
             * Get second Object -> Map -> Find matching Name ->
             * Keep the Name Value -> (Calculate) and Add Points ->
             * Push to State
             */
          }
          })}
    }

  return (
    <div>App</div>
  )

export default App

I’ve tried it with Object.entries, but only the last item was updated and the others were empty.

Thanks for your help!

JavaScript to find all files and create URL paths to them [duplicate]

I am building a math ebook, the pages of said ebook are built with HTML because the author will be adding his work via markup after my work is complete. Using HTML/CSS/JS and installed node.

I need a script that will find all directories and their associated files, then create an array of all the paths to them, so that I may use them to dynamically add a navigation bar.

File structure is as such:

index.html
chapters
| chapter_1
| |-- page_1.html
| |-- page_2.html
| chapter_2
| |-- page_1.html
| |-- page_2.html
| chapter_3
| |-- page_1.html
| |-- page_2.html

etc.

I will then have a navigation bar dynamically added to all pages so that the reader may jump to pages, like a TOC.

<nav>
  <ul>
    <li><a href="I-need-this-url">Chapter 1</a></li>
    <li><a href="I-need-this-url">Chapter 2/a></li>
  </ul>
</nav>

etc.

Can JavaScript find my file structure, create URL paths to all my files, and store it in an array (or something similar to that), so that I can use a for-loop (or map()) to loop through the array and export the paths?

Error with getting ID of current tab in Google Chrome extension in Manifest V3: Uncaught TypeError: Cannot read properties of undefined (reading ‘id’)

I am currently attempting to create a Google Chrome extension in Manifest V3 and keep encountering the following error:

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

I’ve searched far and wide and every solution I’ve found just leads me to stumble into a slightly different error. I’m still pretty new with Javascript, so I’m sure this is just a super noob mistake I’m making, but here is all of my code anyways:

index.html

<html>
    <head>
        <link rel="stylesheet" href="styles.css">
        <link rel="chart" href="Chart/setup.js">

        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@700&display=swap">
        <link rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
        <script type="js/main.js" src="https://www.gstatic.com/charts/loader.js"></script>
    </head>
    <body>
        <div id="donutchart" style="width: 900px; height: 500px;"></div>
        <h4>GOOGLE CALENDAR</h4>
        <h5>Time Tracker</h5>
        <hr></hr>
    </body>
</html>

manifest.json

{
    "manifest_version": 3,
    "name": "Google Calendar Time Tracker",
    "description": "Base Level Extension",
    "version": "1.0",
    "action": {
        "default_popup": "index.html",
        "default_icon": "hello_extensions.png"
    },
    "background": {
        "service_worker": "js/main.js"
    },
    "permissions": [
        "scripting",
        "tabs",
        "https://*/*",
        "http://*/*"
    ]
}

main.js

function getTabId() {
    let tabs = chrome.tabs.query({currentWindow: true, active : true});
    return tabs[0].tabId;
}

chrome.scripting.executeScript({
    target: {tabId: getTabId()},
    files : ["chart.js"],
})
.then(() => console.log("Script injected"));

chart.js

google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work', 11],
        ['Eat', 2],
        ['Commute', 2],
        ['Watch TV', 2],
        ['Sleep', 7]
    ]);

    var options = {
        title: 'My Daily Activities',
        pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
}

Any other suggestions for improvements are more than welcome! As of now, all I’m trying to do is import the Google Charts library successfully, and have a pi chart display within my extension. I didn’t include the stylesheet in the code above, since I didn’t think it would be necessary.

I’ve tried changing id to tabId, and tried with promises as well, and none of that has worked and I’ve just had errors being thrown left, right, and center. It seems like the id / tabId variable just isn’t being recognized at all, but all solutions I saw online utilized it. What am I missing here?

Context is clearing on page reload

I am currently building a react app and am in the beginning stages of setting up my user authentication. The actual user management is pretty easy, as I am using a database service (Supabase) that handles all the user authentication / session management for me. However, I have run into an issue with conditionally rendering parts of my app based on whether or not the user is signed in. For example, I am wanting to render a different navigation bar with different buttons based on if there is a user signed in or not. I have created a custom hook to hold all the sign in stuff from supabase and am attempting to create a context that I can reference elsewhere in the app. My context seems to be giving me trouble though. When I initially log in with a valid user, everything works as expected. I can see the user ID in the context store, and my navigation bar renders according to a logged in user. However, I have found that if I reload the page, my context value clears. Here is the code where I am initializing my context (please note my use of typescript):

import React, { useEffect } from "react";
import { createContext, useContext, useState } from "react";
import useCurrentUser from "../hooks/useCurrentUser";
import supabase from "../supabaseClient";

type TestT = [String, React.Dispatch<React.SetStateAction<String>>];

const UserContext = createContext<TestT>(undefined!);

export function useUser() {
  return useContext(UserContext);
}

export function UserProvider({ children }: any) {
  console.log("IN USER PROVIDER");
  console.log(useCurrentUser());
  const [test, setTest] = useState(useCurrentUser()!);
  return (
    <UserContext.Provider value={[test, setTest]}>
      {children}
    </UserContext.Provider>
  );
}

export { UserContext };

So here is the problem. You will notice I am setting the value in the Provider to a state value, which is defaulting to my useCurrentUser hook. However, when I reload the page, I can see in react dev tools that the ‘test’ state, and therefore the Provider value, are being set to undefined. This is perplexing, because just prior to setting the ‘test’ state value to the useCurrentUser hook value, I am printing it, and it does in fact print a valid user ID. So, I am confused why, even though useCurrentUser DOES have a value, it is not setting to my state value and provider value. What am I doing wrong here? How can I get my context to retain the user ID even when the page reloads?

How recover images group users before render item

I have to recover data before print images in item of a flatList but images array is empty when exit to the function. How I can recover ths array when is a group chat?

Thanks for advance

<FlatList
    data={userChats}
    renderItem={(itemData) => {
        const chatData = itemData.item;
        const chatId=chatData.key;
        const isGroupChat=chatData.isGroupChat;
        let title="";
        const subTitle= chatData.latestMessageText            || "Nuevo chat";
        let images=[];
        if(isGroupChat){
            title=chatData.chatName;
            chatData.users.forEach(uid => {
                let user=storedUsers[uid];
                console.log("CLSuser:"+JSON.stringify(user))
                    if(user){
                        
                    images=[...images, ...user.images]
                    console.log("user.images"+user.images)
                    }
            });
          
        }else{
            const otherUserId = chatData.users.find(uid => uid !== getCurrentUser().uid);
            const otherUser =storedUsers[otherUserId];
            if(!otherUser) return;

            title=`${otherUser.displayName}`;
            images=otherUser.images;
            
        }
   
        return <DataItem title={title} 
        subTitle={subTitle} images={images}
        onPress={()=>props.navigation.navigate("ChatScreen",{chatId})}/>

Is create react app supposed to be used in production?

I’ve mostly been using CRA in all of my react projects. In the past, I’ve only been working in development, not ever pushing to production. I just recently tried to push to production, and the size of my project (that I developed with CRA) was gigantic, like 25 GB for a pretty simple file. After doing some researching, I now know that CRA and the pre-installed node_modules is really clunky and large.

So is CRA ever really used in production, or is it better to use babel/webpack? Is it sometimes better to develop with CRA due to pre-built stuff, but use webpack / babel combo when its time to push to production?

Thanks!

Preciso obter o id [closed]

Estou tentando obter o valor de uma id com javascript mas ocorre o mesmo erro toda vez: Uncaught TypeError: this.getAttribute is not a function

let links = document.querySelectorAll('.add');
for(var i = 0; i < links.length; i++){
    links[i].addEventListener('click', ()=>{
        let key = this.getAttribute('id');
        console.log(key);
    });
}

Gostaria de obter este id mas sempre aparece o mesmo erro precis de ajuda pfv

How to retrieve a dropdown select content that only gets populated after first time opening? Google Slide Presenter

Google Presenter (in fullscreen window mode) provides a dropdown to select Slides, which only populates a div goog-menu goog-menu-verticalonce it has been opened the first time.

Is there any way to find out from where Google is pulling this info, whether I can access the Slide titles without having to trigger a mousedown event to simulate the opening/closing action?

Otherwise the only workaround I can see is to open and close it via javascript and maybe hide it first so the action is invisible, but I’d prefer to access the data directly if possible. How best to check in dev console?

I wan to extract textContent from .goog-menuitem-content contained inside goog-menu-verticaldiv class (only available once select had been opened).

enter image description here

enter image description here

GUI Programming drag and drop fundamental to generate code in behind

what is the concept of GUI programming like arduino GUI. When we arrange the block, the code in underlaying is changed too. even we put it in the middle or on the top. how does the logic work ? do you have reference to be deep of fundamental how to make sequence like that.

need understand the fundamental how to do it, from beginning, so i can make simple example for my learning