Change the image src of a div element in a grid on a keypress event in React

I am building a navigable grid with arrow keys. Everything works fine, but I would like the focused element to change the img when selected from an img to a gif.

I tried to give it the same name that I used to import the image, like the element id tag. But this didn’t work. React interprets the id tag as a string and not the path name to that image.

Any ideas how to get React to interpret the element ID as the image path to look up?

import items from './assets/images/items.png'
import items2 from './assets/images/items.gif' 
 useEffect(() => {
                let i = 0 
                const handleKeyPressed = (e) => {
                        //to focus the right element
                        if (['KeyD', 'ArrowRight'].includes(e.code) ) {
                                i = ++i
                                let menuElement= document.getElementsByClassName('menu-image')[i]
                                menuElement.style.border="solid 3px"
                                const dynamicString = document.getElementsByClassName('menu-image')[i].id
                                menuElement.src=dynamicString//React interprets it as a string
 
                                
                        }
                }
                window.addEventListener('keydown', handleKeyPressed);
                return () => {
                window.removeEventListener('keydown', handleKeyPressed);
                };
}, []);
<div className='menu-grid'>
                <div className="menu-item">
                    
                <img id="items" className="menu-image" alt="a draw of a bag" src={items2} style={{ border: 'solid 3px'}}
                        onPointerOver={e => {
                                e.currentTarget.src = items2
                                e.target.style.border="solid 3px"} 
                        } 
                        onPointerLeave={e => {
                                e.currentTarget.src = items
                                e.target.style.border="solid transparent 3px"}
                        }/>
                        <span> Items </span>
                    
                </div>
</div>

Getting a callback after a request has been completed in a Gmail Add On in Apps Script

First of all what I am trying to do is accomplish the following.
Note: this is not my add-on.

How is this script generated? I cannot find any information about script.google.com/macros.

enter image description here

After this tab is closed, the add-on gets a callback that looks like this.

enter image description here

enter image description here

I don’t understand the flow. How does the add-on script know that the tab is being closed? How is the script created? At which endpoint does the script call the google add-on?

The following is my add-on script:

function insertDocumentToRMS(e){
   var url = "https://test.signumid.hr/v/1/rms";

  var object = {
    "data" : e.parameters.file.toString()
  }

  var payload = JSON.stringify(object);

  var headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
  };

  var options = {
    "method": "POST",
    "contentType": "application/json",
    "headers": headers,
    "payload": payload,
    "muteHttpExceptions": true
  };
  

  var response = UrlFetchApp.fetch(url, options);
  var data = JSON.parse(response.getContentText());
  
  Logger.log(data);

  var url2 = "https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber;

  Logger.log(url2);

  var object2 = {
    "SignatureProvider": "SwisscomAis",
    "SignatureProviderData": {
      "SwisscomRequestData": {
        "mobileNumber": "+41796063855",
        "language": "en",
        "message": "Matej PotpiĆĄiii!",
        "jurisdiction": "ZERTES",
        "signatureLevel": "AES"
      }
    },
    "Documents": [
      {
        "SignatureOptions": {
          "Reason": "Reason",
          "Location": "Location",
          "SignerContactInfo": "SignerContactInfo",
          "SignerName": "SignerName"
        },
        "Document": e.parameters.file.toString()
      }
    ]
  }

  var payload2 = JSON.stringify(object2);

  var headers2 = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
  };

  var options2 = {
    "method": "GET",
    "contentType": "application/json",
    "headers": headers2,
    "payload": payload2,
    "muteHttpExceptions": true
  };
  
  var response2 = UrlFetchApp.fetch(url2, options2);
  Logger.log(response2);

let actionSign = CardService.newAction().setFunctionName('test');

var actionResponse = CardService.newActionResponseBuilder()
    .setOpenLink(CardService.newOpenLink()
        .setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
        .setOpenAs(CardService.OpenAs.OVERLAY)
        .setOnClose(CardService.OnClose.RELOAD))
    .build();
   

  return actionResponse;
}

As you can see at the end (here), I am trying to use an actionBuilder with an actionResponse that has the property OnClose, but the only parameters on OnClose are: NOTHING and RELOAD. Can i pass an action somehow or what am i supposed to do to replicate the scenario that i mentioned above?

var actionResponse = CardService.newActionResponseBuilder()
    .setOpenLink(CardService.newOpenLink()
        .setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
        .setOpenAs(CardService.OpenAs.OVERLAY)
        .setOnClose(CardService.OnClose.RELOAD))
    .build();

Javescript create list of numbers 0 to n

Sorry, I dont know anything about programming, so bare with me.
I need an expression for a textlayer in adobe after effects which uses javascript. The expression needs to create a customizable list of numbers using 3 variables –
example:

x = 0 //starting point (the first number in the list)
y= 20 //increments (the size of the steps)
z= 5 //the number of steps

the output needs to be a list with each entry in a new line, in this case:

0
20
40
60
80

Hope somebody can help. Thanks

How to get a specific attribute value content on each loop jquery

Can anyone tell me how I can get all the values on a specific attribute value on each loop ? I’m trying to get all the values on each loop with the specific attribute ( data-product ) in this case..

This is my code

<script>
    jQuery( document ).ready(function() {
        $(".compare-main .compare-products").each(function(){
                $(this).each(function(){
                    console.log($(this).html());
                })
            });
        });
</script>

enter image description here

Remove duplicates from an array within an array [duplicate]

What is the best way to see remove duplicate value of an array in JavaScript object if the duplicate value is also of type object.

I made a simple example down below.

onlyUnique seems to only work with standard arrays such as
var data2 = [1,2,4,4,4,5]

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}

var data = [['true', 'visiting-today', 'DVM-Wiessman','J-001'],
['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['false', 'visiting-tommorrow', 'DVM-Kon','J-001']];

data = data.filter(onlyUnique);

result

var data = [['true', 'visiting-today', 'DVM-Wiessman','J-001'],
['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['false', 'visiting-tommorrow', 'DVM-Kon','J-001']];

goal

var data = [['true', 'visiting-today', 'DVM-Wiessman','J-001'],
['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['false', 'visiting-tommorrow', 'DVM-Kon','J-001']];

JS function does not work after ajax request

I’ve been struggling all day now why a certain JS function stopped working after an AJAX request is called. It must have something to do with the query selector. But I just can’t figure out what’s going on there!

( function() {
    'use strict';

    if ( 'querySelector' in document && 'addEventListener' in window ) {
        const select = document.querySelectorAll( '.Accordion-panel select' );
        const input = document.querySelectorAll( '.Accordion-panel input' );

            if ( select.selected ) {
                document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'true' );
                document.getElementsByClassName( 'Accordion-panel' ).removeAttribute( 'hidden' );
            } else {
                document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'false' );
                document.getElementsByClassName( 'Accordion-panel' ).setAttribute( 'hidden', '' );
            }

            if ( input.checked ) {
                document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'true' );
                document.getElementsByClassName( 'Accordion-panel' ).removeAttribute( 'hidden' );
            } else {
                document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'false' );
                document.getElementsByClassName( 'Accordion-panel' ).setAttribute( 'hidden', '' );
            }

        document.addEventListener( 'click', function( event ) {
            const target = event.target;

            if ( target.classList.contains( 'Accordion-trigger' ) ) {
                // Check if the current toggle is expanded.
                const isExpanded = target.getAttribute( 'aria-expanded' ) == 'true';

                if ( ! isExpanded ) {
                    // Set the expanded state on the triggering element.
                    target.setAttribute( 'aria-expanded', 'true' );
                    // Hide the accordion sections, using aria-controls to specify the desired section.
                    document.getElementById( target.getAttribute( 'aria-controls' ) ).removeAttribute( 'hidden' );
                } else {
                    // Set the expanded state on the triggering element.
                    target.setAttribute( 'aria-expanded', 'false' );
                    // Hide the accordion sections, using aria-controls to specify the desired section.
                    document.getElementById( target.getAttribute( 'aria-controls' ) ).setAttribute( 'hidden', '' );
                }

                event.preventDefault();
            }
        }, false );
    }
}() );

Currently I use the function without a loop. This means that the function can still be called after an ajax call.

Furthermore, I want that when a user has selected a field (select or checkbox) that I keep the current accordion open after an ajax request!

Here is a jsfiddle to take a closer look https://jsfiddle.net/5p713cty/1/

Thanks in advance!

I have Failed to construct ‘FormData’: parameter 1 is not of type ‘HTMLFormElement’ on my devtools

I want to send my form with form data, method POST, with Fetch API in JavaScript but I have an error.
Why I have this : runtime-core.esm-bundler.js?d2dd:218 Uncaught TypeError: Failed to construct ‘FormData’: parameter 1 is not of type ‘HTMLFormElement’.

My project is based on vue.js, express.js and mysql.
I haven’t started the backend part of the function signup in (router/controllers). But normally nothing to do with the error that is displayed

When the request returns me a code 200 at this time I can make my backend which uses express.js.
Thank you for your help.

//Vue.JS

<script>
export default {
  name: "FormSuscribe",
  data() {
    return {
      email: " ",
      password_key: "",
    };
  },
  methods: {
    submitForm() {

      const formData = new FormData(this);

      fetch("http://localhost:8080/api/auth/signup", {
        method: "POST",
        body: formData,
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (json) {
          console.log(json);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};

</script>
<form
    method="post"
    @submit="submitForm()"
    class="d-flex flex-column justify-content-center align-items-center"
  >
   

    <div class="form-group col-lg-5">
      <label class="form-control-label">Email</label>
      <input
        type="text"
        class="form-control"
        id="formGroup2"
        placeholder="@"
        v-model="email"
        name="email"
        required
      />
    </div>
    <div class="form-group col-lg-5">
      <label class="form-control-label">password</label>
      <input
        type="password"
        class="form-control"
        id="formGroup1"
        placeholder="*******"
        name="password_key"
        v-model="password_key"
        required
      />
    </div>
    <div class="form-group">
      <button type="submit" value="Submit" class="btn fw-bold mt-4">
        Inscription
      </button>
    </div>
  </form>

Transform json array to typescript array with different schema

I need to transform a JSON response to a typescript array which has different a different schema

method to get the json response

getCalendarShipments(params?: HttpParams): Observable<Shipment[]> {
  return this.http.get<Shipment[]>(this.baseUrl + 'shipments', {params});
}

Current method to map the response:

events: CalendarEvent[] = [];
this.customerService.getCalendarShipments(this.httpParams)
.pipe(map((result: Shipment[]) => result.forEach(e => {
     this.events = [{
         start: new Date(e.appointmentTime),
         end: new Date(e.appointmentTime),
         title: e.container
     }, ];

}))).subscribe();

In the above code, i’m using a foreach to iterate over the array and trying to add a new object with the relevant data to the typescript array, but to no luck. I have also tried using the push method to add the objects that way.

The events array has a different schema than the Shipments model

Firefox extension – retrieve href from class |works| – opening new window or start to download from given url – not working

I wrote an extension that should get the content of a specific href link. It should then open the url without user interaction.

The script I’ve been working on so far gets the correct url. It can print the url in a push notification. The basics of the FF extension work.

But no matter what I’ve tried (open.window, browser.downloads., window.location) never has a window opened or the download started when visting the domain / website containing the hidden–Element.

I’m a total beginner but I would like to get this script to work. This would motivate me to keep on learning.

This is the manifest.json


"manifest_version": 2,
"name": "Adskipper",
"version": "0.97",

"description": "Skip the Countdown and download instantly",
"permissions": ["downloads.open", "downloads", "webRequest", "tabs"],

"icons": {
    "48": "icons/adskip_48.png",
    "96": "icons/adskip_96.png"
  },

"content_scripts": [
{
    "matches": ["*://*.thedomain.org/*"],
    "js": ["border.js", "jquery-3.6.0.min.js", "adskip.js"],
"run_at": "document_end"


}


]

} 

this is the content of adskip.js

for(var i=0; i<l.length; i++) {
  arringo.push(l[i].href);
}


alert(arringo);
    
/* function onCreated(tab) {
  console.log(`Created new tab: ${tab.id}`)
}

function onError(error) {
  console.log(`Error: ${error}`);
}

browser.browserAction.onClicked.addListener(function() {
  var creating = browser.tabs.create({
    url:"https://www.duckduckgo.com"
  });
  creating.then(onCreated, onError);
});

onCreated();

*/

/* browser.downloads.download({url: "https://ir.ebaystatic.com/rs/v/fxxj3ttftm5ltcqnto1o4baovyl.png"});
*/

*/ These are the approaches I tried at the end. I’ve tried different approaches but still had no luck to open the url from the var arringo
*/

Comments:
border.js is just loaded to see if the extension works

jquery has been added since I tried a jquery approach on it. If possible I don’t want to include it.

I added the permissions in the manifest.json but I’m not sure whether I need them / another ones / or not at all.

Please don’t downvote my question again. I tried everything to comply with the stackoverflow guidelines.

Dynamically parsing arrays in HTML using ng-repeat

I am a newbie to JS and HTML, sorry if these questions are very basic . I am trying to create a HTML table using ng-repeat by parsing an JS array. The example is given below

  1. I would have multiple rows stored in an array like the one given below. I need to use ng-repeat to dynamically build an HTML Table like the one given below, in the same order

HTML Table structure

There could be multiple runs like run3, run4 etc, which has multiple variables in it. Kindly help

  1. Also i am pushing data into these arrays in different order, but i believe they are sorted alphabetically as shown below. i need them in the order which is given in the image or the the order they are pushed in.

sample record:

{"acceptable":12,"run2":{"avg":0,"percent":0},"run1": {"avg":"9.337","percent":"10.401"},"trname":"ESSCreateIncident","target":8},

Mongodb findOneAndUpdate replaces other values on PATCH

I’m working on an API, in my frontend, I send a PATCH request to a route that can update weight, height or gender. The structure of my schema model is this:

/** @format */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    userNumber: { type: Number, required: true },
    description: { type: String },
    verified: { type: Boolean, default: false },
    isAdmin: { type: Boolean, default: false },
    isSubscriber: { type: Boolean, default: false },
    isDisabled: { type: Boolean, default: false },
    characteristics: {
      height: { type: Number, default: 0 },
      weight: { type: Number, default: 0 },
      gender: { type: String, default: 'other' },
    },
    acceptedTerms: { type: Number, required: true },
  },
  { timestamps: true }
);

module.exports = mongoose.model('User', userSchema);

Now my controller actions are quite similar to find update those 3 values:

exports.changeSex = async (req, res, next) => {
  // Requirements
  const userId = req.params.userId;
  const newGender = req.body.gender;

  console.log('userId: ' + userId);
  console.log('newGender: ' + req.body.gender);

  try {
    const user = await User.findOneAndUpdate(
      { _id: userId },
      { characteristics: { gender: newGender } }
    );
    console.log('User successfully updated.');
    return res.status(200).json({ success: true, gender: newGender });
  } catch (err) {
    console.log('ERROR: ', err);
    return res.status(400).json({ success: false, error: err });
  }
};

The problem I’m facing is each time I execute one of these 3 actions, one replaces the others.

For example, changing gender, will output height: 0, and weight: 0, and if I update weight: 10, gender returns to gender: ‘other’.

It seems findAndUpdateOne replaces everything using the default values of my schema, which would be a pity to rewrite the entire thing, I tried updateOne and I find the same result. I also tried this:

...
try {
    const user = await User.findOneAndUpdate(
      { _id: userId },
      { $set: { characteristics: { gender: newGender } } }
    );
...

and also:

try {
    const user = await User.findOneAndUpdate(
      { _id: userId },
      { characteristics: {$set { gender: newGender } } }
    );

And both examples also repeat the same pattern.

Flask Plotly Responsive in Browser

How to make this plotly chart responsive in index.html – I create a flask app and js function for rendering the plot, however, I cannot figure out, how to make it responsive. What is wrong with variable config – it seems not to work.

Thank you

Flask:

@app.route('/')
def index():

    locations = sorted(df['location'].unique())
    rooms = sorted(df['rooms'].unique())

    # Visualisation
    import json
    import plotly
    import plotly.express as px
    df.rooms = df.rooms.astype(str)
    fig = px.scatter(df, x="m2", y="price", trendline="ols", color="rooms", symbol='rooms',
                                marginal_x="histogram", 
                                marginal_y="rug",
                                template='plotly_dark', hover_data=['price', 'rooms', 'm2', 'location'],
                                title="Real Estate in Vienna")
    
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return render_template('index.html', locations=locations, rooms=rooms, graphJSON=graphJSON)

JavaScript:

                    <!-- Visualisation -->
                    {%block content%}
                    <div class="card mb-4 m-auto" style="width: 90%">
                        <div class="card-body">
                            <div id="chart"></div>
                        </div>
                    </div>
                    {% endblock %}

    <!-- Plotly -->
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script type="text/javascript">
        var graphs = {{ graphJSON | safe}};
        var config = {responsive: true};
        Plotly.newPlot("chart", graphs, {}, config);
    </script>

Can not get the element

Hello so when I try to get the tbody element in JavaScript I get the error that it is null
But whenever I use the same method to get the element but in a different file it works perfectly.

I have tried getting the element by id and class but nothing seems to be working.

Here is my HTML:

<table class="table table-striped" >
    <thead>
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Photo</th>
            <th scope="col">Price</th>
            <th scope="col">Operation</th>
        </tr>
    </thead>
    <tbody>
        
    </tbody>
</table>

And my JavaScript:

function newPc() {
    let hiding = document.getElementsByClassName("hiding");

    hiding[0].classList.remove("hiding");
    // hiding[1].classList.remove("hiding");
}

function newSub() {
    if (localStorage.getItem("counter-for-new-computers") == null) {
        localStorage.setItem("counter-for-new-computers", 0);
    }

    const information = document.getElementsByClassName("information");


    const category = information[0].options[information[0].selectedIndex].value;
    console.log(category)

    const ram = information[1].value;
    console.log(ram);

    const name = information[2].value;
    console.log(name);

    const cpu = information[3].value;
    console.log(cpu);

    const price = information[4].value;
    console.log(price);

    const rom = information[5].value;
    console.log(rom);

    const about = information[6].value;
    console.log(about);

    const rom_type = information[7].options[information[7].selectedIndex].value;
    console.log(rom_type);

    const condition = information[8].options[information[8].selectedIndex].value;
    console.log(condition);

    const os = information[9].value;
    console.log(os);

    const url = information[10].value;
    console.log(url);

    const gpu = information[11].value;
    console.log(gpu);

    const data_of_new_computers = category + "---" + ram + "---" + name + "---" + cpu + "---" + price + "---" + rom + "---" + about + "---" + rom_type + "---" + condition + "---" + os + "---" + url + "---" + gpu;
    console.log(data_of_new_computers);
    let id = localStorage.getItem("counter-for-new-computers");
    localStorage.setItem("data_for_new_computers-" + id, data_of_new_computers);
    localStorage.setItem("counter-for-new-computers", ++id);



    return true;
}

function newTable(data_base, i) {


    const tr = document.createElement("tr");

    const td_id = document.createElement("td");

    const td_name = document.createElement("td");

    const image = document.createElement("img");

    const td_image = document.createElement("td");

    td_image.appendChild(image);

    const td_price = document.createElement("td");

    const td_operation = document.createElement("td");

    const operation = document.createElement("button");

    td_operation.appendChild(operation);

    td_id.textContent = i;

    td_name.textContent = data_base.naming;

    image.src = data_base.url;

    image.alt = "Couldn't load image";

    td_price.textContent = data_base.price;

    operation.setAttribute("click", "sitDown()");



    tr.appendChild(td_id);
    tr.appendChild(td_name);
    tr.appendChild(td_image);
    tr.appendChild(td_price);
    tr.appendChild(td_operation);
    data_base.body.appendChild(tr);

};




function giveMe() {
    for (let i = 0; i < localStorage.getItem("counter-for-new-computers"); i++) {

        const data = localStorage.getItem("data_for_new_computers-" + i);
        console.log(data);

        const data_base = {
            category: data.split("---")[0],
            ram: data.split("---")[1],
            naming: data.split("---")[2],
            cpu: data.split("---")[3],
            price: data.split("---")[4],
            rom: data.split("---")[5],
            about: data.split("---")[6],
            rom_type: data.split("---")[7],
            condition: data.split("---")[8],
            os: data.split("---")[9],
            url: data.split("---")[10],
            gpu: data.split("---")[11],
            body: document.getElementsByTagName("table")[0],
        }

        newTable(data_base, i);
    }
}

giveMe();