After clicking on the button, the input new value returns to the old value

I need advice, I’m doing such an extension JS, but maybe I’m making a mistake in that the app runs on Angular

var input1 = document.getElementsByClassName("vypln")[0];

var enter = new CustomEvent('keyup');
enter.which = 13;
enter.keyCode = 13

input1.focus();input1.value="";
document.execCommand('insertText', false, 4);
input1.dispatchEvent(enter);

document.getElementsByClassName('buttons')[0].querySelector('button').click();

The data is written to the input, … but after clicking on the button, the old value is set. I want value to stay there and do it.
Interestingly, if I use this code and then click (mouse / manually) anywhere and then call document.getElementsByClassName('buttons')[0].querySelector('button').click(); so it works fine.
Thank you all for the advice)

how to pop up datalist options for input tag in html

I’m currently trying to add to my datalist for my input text field in html. The way I do it is to retrieve text from backend and dynamically generate options in datalist, however, after I retrieve all texts at my frontend and generate option to datalist, there is only one option display instead all.

Here is the way I add option to my datalist:

async function getSuggestedWords(event) {
    let datalist = document.getElementById("suggestions");
    let text = document.getElementById("q").value;
    let http = new XMLHttpRequest();
    http.responseType = "json";
    // let str = "";
    http.onload = async function() {
        if (this.readyState == 4) {
            let  {suggestions}   = http.response;

            for (let suggest of suggestions) {
                console.log(suggest.term);
                let s = document.createElement('option');
                s.setAttribute("value", suggest.term);
                datalist.appendChild(s);
            }
        }
    }

    const url = `http://localhost:8080/api/suggest?q=${text}`;
    await http.open("GET", url);
    await http.send();
}

here is my html:

        <label for="q">Input</label>
        <input type="text" name="q" id="q" list="suggestions" onchange="getSuggestedWords(event)" autocomplete="on">
        <datalist id="suggestions">
        </datalist>

Nextjs passing ids to through link

I’ve created a component named ArticleList this component’s purpose is to display a list of articles that are returning from an API. When clicking on the article title it will redirect to that individual page which I’ll then fetch data for. The API used needs an article id parameter which I have access on the ArticleList component. I am having issues passing this id to the [...blog] page I created.

How can I redirect to this dynamic blog page without passing the ID in the URL? If I’d like to show the id in the URL then I would not have any issues as I can access it from next.js router but because I do not want it in the URL I am having issues with coming up with an alternative working way.

I’ve attempted to do some research if possible, to hide the query strings in the URL when on the page but based on my research that does not look like it is possible in next.js. Also based on my research there is no next/Link property I can use to pass this without displaying it in the URL.
The code snippet I am having issues with is:

 <Link href={`/blog/${ConvertCodeTitleToURL(d.name)}`}>
      <a className="text-body-black font-weight-500 letter-spacing-15 text-20 m-b-8">
          {article.title}
         </a>
   </Link>

Here is an example of the ArticleList component:

import Image from "next/image";
import Link from "next/link";

function ConvertCodeTitleToURL(title) {
  let url = "";

  if (title) {
    url = title.replace(".", "").toLowerCase();
    url = url.replace(/,/g, "");
    url = url.replace("(", ""); // added for (except) cases
    url = url.replace(/s/g, "-");
  } else {
    url = "/";
  }

  return url;
}

const ArticleList = ({ categories, articles }) => {
  let combinbedarr = categories.results.map((item, i) =>
    Object.assign({}, item, articles[i])
  );

  return (
    <div className="container-1200">
      {combinbedarr &&
        combinbedarr.map((d) => (
          <>
            {d.results.length > 0 && (
              <div key={d.id}>
                <div className="d-flex justify-space-between">
                  <div className="heading-30 letter-spacing-25 text-dark-blue m-l-n-20">
                    {d.name}
                  </div>
                  <Link
                    href={`/categories/${ConvertCodeTitleToURL(d.name)}/?id=${
                      d.id
                    }`}
                  >
                    <a className="text-16 font-weight-500 letter-spacing-25 text-blue m-r-120">
                      All {d.name} <i className="fas fa-arrow-right"></i>{" "}
                    </a>
                  </Link>
                </div>
                <div className="d-flex align-center m-b-32 flex-wrap">
                  {d.results &&
                    d.results.map((article) => (
                      <>
                        <div className="m-r-32 card-resources">
                          <div
                            key={article.id}
                            className="m-b-20 ct-relative card-resources-img m-b-20"
                          >
                            <img
                              className="div-100"
                              alt=""
                              layout="responsive"
                              height="180"
                              src={`test.api.com/${article.seoImageUrl}`}
                            />
                          </div>

                          <div className="article-content">
                            <Link
                              href={`/blog/${ConvertCodeTitleToURL(d.name)}`}
                            >
                              <a className="text-body-black font-weight-500 letter-spacing-15 text-20 m-b-8">
                                {article.title}
                              </a>
                            </Link>
                            <div className="m-b-20">
                              {article.seoDescription}
                            </div>
                            <div className="d-flex m-b-20">
                              {article.tags &&
                                article.tags.map((tag) => (
                                  <div className="ct-topics" key={tag}>
                                    {tag}
                                  </div>
                                ))}
                            </div>
                          </div>
                        </div>
                      </>
                    ))}
                </div>
              </div>
            )}
          </>
        ))}
    </div>
  );
};
export default ArticleList;

[...blog] page that I would like to have access to the id

const blog = () => { 
    // logic to fetch article data using the ID from `ArticleList`
return (
<div></div>

    )
}
  

export default blog 

Sending a function with a parameter through an .onclick listener

I’m a beginner web developer who is in the process of putting together a simple website that will use an API to display data from various cities based on different buttons a user can click. I’ve written a general function that takes in a city parameter, runs it through the api and sends the appropriate data back to my HTML page. I’m just having trouble getting the event listener for my buttons to work as expected.

Listener examples:

city1button.onclick = cityInfo("city1");
city2button.onclick = cityInfo("city2");

Based on some research, I now realize that my code is invoking my functions before a button can be pressed. I’ve found some more elaborate solutions online, but was wondering if there is a simple way that could ideally be kept in one line. Thanks in advance. I really appreciate the help.

A-Star pathfinder for a Canvas sprite using javascript?

I am trying to make a 2d game using javascript Canvas, but I need the sprites to be able to navigate around the map using AStar (or something similar). I’ve tried researching a bit into this, but I can’t manage to understand how to do what I want. I need the pathfinding function to return the path as a list of consecutive coordinates to go towards in order to get to the target tile.
Would someone be able to make a function (or point me in the direction of one) that would do something like this:

var map =
  [
    [0, 0, 1, 0, 1],
    [1, 0, 1, 0, 0],
    [0, 0, 0, 1, 0],
    [0, 1, 0, 0, 1],
    [0, 0, 1, 1, 1],
    [1, 0, 0, 0, 1]
  ]
var currentPos = [0, 0];
var targetPos = [5, 3];

function pathFind(map, start, end) {
 // Coding Stuff......
}

listOfMovesToMake = pathFind(map, currentPos, targetPos);
// returns array of coordinates
// i.e. [ [0, 1], [1, 1], [2, 1], [2, 0], [3, 0], [4, 0], [4, 1], [5, 1], [5, 2] ]

I like the concept of pathfinding, but the math and brain power required is painful.
Thanks to anybody that can help.

group array of object by property value

I have this array of objects:

[
 {
   day: 1,
   status: red,
   count: 3
 },
 {
   day: 1, 
   status: blue,
   count: 5
 },
 {
   day: 2,
   status: red,
   count: 10
 },
 {
   day: 2,
   status: blue,
   count: 1
 }
]

I want to re-factor this array into a new array and group by the day value:

[
 {
   day: 1,
   statusSummary: [
     {
       status: red,
       count: 3
     },
     {
       status: blue,
       count: 5
     }
   ]
 },
 {
   day: 2,
   statusSummary: [
     {
       status: red,
       count: 10
     },
     {
       status: blue,
       count: 1
     }
   ]
 }
]

what is the most efficient way to do this?

Visibility of arrays in javascript (“undefined”)

I tried to calculate the sum of two matrizes (multi-dimensional-arrays), but I get the following error-message:

Uncaught TypeError: Cannot set properties of undefined (setting '0')
    at matAdd (matrixCalc.js:28)

when I do this code↓. I don’t understand why “matSum[0][0]” is undefined.

// M1 + M2
function matAdd(m1, m2){        
    let matSum = new Array(m1.length);
    for (let i=0; i<m1.length; i++){       //create a blanco-matrix
        matSum=new Array(m1[0].length);
    }
    
    if (m1.length == m2.length && m1[0].length==m2[0].length){
        for (let i=0; i<m1.length; i++){
            for (let j=0; j<m1[0].length; j++){
                matSum[i][j]=m1[i][j]+m2[i][j];                  //HERE THE ERROR OCCURS
            }
        }
    }
    else console.log("Dimension-Error")
    return matSum;
} 

the code with line-numbers

Thx for the help 🙂

Counting word in message how to save

Here’s my code and my question is how can i change it to save numbers of counting?

After restart script it always back to 0

I don’t want change manually var test = 0;

const tmi = require('tmi.js'),
    { channel, username, password } = require('./settings.json');

const options = {
    options: { debug: true },
    connection: {
        reconnect: true,
        secure: true
    },
    identity : {
        username,
        password
    },
    channels: [
                '#qwerty',
    ]
};

var test = 0;

const client = new tmi.Client(options);
client.connect().catch(console.error);

client.on('connected', () => {
    client.say(channel, `Here`);
});

client.on('message', (channel, user, message, self) => {
    if(self) return;

        if(user.username == 'zzz' && message.includes('SSS')) {
            test++;
        }
        if(message == ('test')) {
            client.say(channel, 'xxx ' + test.toLocaleString());
        }
    });

Jquery post function doesn’t post to php file for some reason

I’m trying to create a function that removes a row from the database once an image is clicked, so far the code works in identifying the order needing to be removed however when I go to use the post function it doesn’t respond in any way. No error no nothing and I can’t see to figure it out, any help would be appreciated.

    <script>
    $(document).ready(function() {
        $('.bins').click(function() {
            
            var name = $(this).attr('name');
            alert(name);
            $.post("cancel.php", {cancels: name})
            alert("bruh moment");
        });
    });
</script>

while ($row = mysqli_fetch_assoc($result)){
                        $order_advanced = implode(",", $row);
                        $order = $row["Order_ID"];
                        $colour = $row["Colour_Custom"];
                        $Ingredient = $row["Ingredients"];
                        $amount = $row['Order_amount'];
                        $photo = "rubbish.png";
                        $_SESSION['Current'] = $order;
                        echo "
                                <tr>
                                    <td>$order</td>
                                    <td>$colour</td>
                                    <td>$Ingredient</td>
                                    <td>$amount</td>
                                    <td><img name = $order id="rubbish" src="rubbish.png" class="bins"></td>
                                </tr>"
                    }
                    


<?php
 if($_SERVER['REQUEST_METHOD'] == "POST") {

    header("Location: account.php");
    include("database.php");
    include("functions.php");
    $order = $_POST['cancels'];
    $query = "delete from designs where Order_ID = '$order' limit 1";
    mysqli_query($con, $query);

    header("Location: orders.php");
    die;
}

?>

How can I use “exports” in package.json today for nested submodules and typescript

I am wanting to take advantage of the new-ish “exports” feature of NodeJS/package.json so that I can do the following:

"exports": {
  ".": "./dist/index.js",
  "./foo": "./dist/path/to/foo.js"
}

And users can do the following:

import { foo } from 'my-package/foo';

Typescript 4.5 should support the “exports” field, yet it does not seem to work. I am building a simple package using TS 4.5.2, and I am consuming that package in a project using TS 4.5.2. I have looked at other SO questions and this github thread and this bug report but can’t seem to find a consensus on the issue.

Note 1: I am still able to import using the more verbose syntax:

import { foo } from 'my-package/dist/path/to/foo.js';

Note 2: I have also tried the object notation for exports, to no avail:

"exports": {
  ".": { "require": "./dist/index.js", "import": "./dist/index.js" },
  "./foo": { "require": "./dist/path/to/foo.js", "import": "./dist/path/to/foo.js" }
}

Question(s):

  1. Is this feature ready to be used with typescript projects today? If not, I just want to know.
  2. If yes to #1, what am I missing? Specifics about tsconfig would be useful for both the source project and consuming project. The TS compiler complains about node12/nodenext being used for either the module or moduleResolution fields.

set token recived from api in axios header

I send a request to the API for creating an account(I use axios) then API send me a response involve a token. I save this token in local storage.But I don’t know how to send it in axios header.

if (this.sendRequest) {
    axios.post(url, data)
      .then((res) => {
        if (res.data.type === "success") {
         localStorage.setItem("token",res.data.data);
        }
      })
      .catch((err) => this.msg.push("error" + err.response.status));
  }

Comparing 2 objects’ values and push the values to one object array

I am trying to compare 2 objects by their property and the values. If the value of the “name” property matches up with each other, I want to push the property and value to value3.

Once value3 is logged, I want the response like this:

{
name: 'dog',
surname: 'good',
skills: 'programming',
age: '22'
},
{
name: 'cat',
surname: 'soft',
skills: 'engineer'
age: '12'
},
{
name: 'elephant',
surname: 'big',
skills: 'programming'
age: '23'
}

Here is the code:

var values1 = [
    {
    name: 'dog',
    surname: 'good',
    skills: 'programming'
    },
    {
    name: 'cat',
    surname: 'soft',
    skills: 'engineer'
    },
    {
    name: 'elephant',
    surname: 'big',
    skills: 'programming'
    }
]

var values2 = [
    {
    name: 'cat',
    food: 'fish',
    age: '12'
    },
    {
    name: 'elephant',
    food: 'leafs',
    age: '13'
    },
    {
    name: 'dog',
    food: 'treats',
    age: '22'
    }
]

// push into this empty object array
var values3 = [{}]

console.log(values3)

ERRO DE NODE_MODULE_VERSION

I have a error, inside project Node_MODULE_VERSION is 82, but outside a project Node_MODULE_VERSION is 93, how can i fix it?
i already downgrade and upgrade, but none of it works.
Outsidea project

{
  "node": "16.13.0",
  "v8": "9.4.146.19-node.13",
  "uv": "1.42.0",
  "zlib": "1.2.11",
  "brotli": "1.0.9",
  "ares": "1.17.2",
  "modules": "93", <<<<<<<<<
  "nghttp2": "1.45.1",
  "napi": "8",
  "llhttp": "6.0.4",
  "openssl": "1.1.1l+quic",
  "cldr": "39.0",
  "icu": "69.1",
  "tz": "2021a",
  "unicode": "13.0",
  "ngtcp2": "0.1.0-DEV",
  "nghttp3": "0.1.0-DEV"
}

Inside a project

{
  "node": "12.16.3",
  "v8": "8.5.210.26-electron.0",
  "uv": "1.34.2",
  "zlib": "1.2.11",
  "brotli": "1.0.7",
  "ares": "1.16.0",
  "modules": "82",<<<<<<<<<<<<<<<<<<<<<
  "nghttp2": "1.41.0",
  "napi": "5",
  "llhttp": "2.0.4",
  "http_parser": "2.9.3",
  "openssl": "1.1.0",
  "icu": "67.1",
  "unicode": "13.0",
  "electron": "10.4.2",
  "chrome": "85.0.4183.121"
}

the erro is in a image:
enter image description here

How to properly catch a HTTP error status code when using fetch?

When you use the fetch API in JavaScript and the result contains a status code that isn’t OK (not 2xx), an error that includes the status code and the method is being logged to the console in most browsers (I’ve tried Chrome, Edge and Opera). This makes sense, as this type of response usually means some kind of error on your side.

However this error is also present when using a .catch chain on your Promise (this is the most basic code example):

fetch("<some api call that returns a status code of 400>")
    .catch(_ => {});

This gives the same error in the console as not catching it.

If .catch(_ => {}) does not work, is there a way to suppress this error?

Typescript – Create custom type from common properties of an Array of object

I have an array of objects, which have a common key “foo” and I am trying to create a custom type out of this property

class Object1 {
   static foo = { reducer_one: {...} }
   object_1_method() {...}
}

class Object2 {
   static foo = { reducer_two: {...} }
   object_2_method() {...}
}

class Object3 {
   static foo = { reducer_three: {...} }
   object_3_method() {...}
}

const myArray = [Object1, Object2, Object3 ];

I am trying to get a reduced object type gathering all the different foo properties of all the initial objects in the array.

const finalObject = {
   reducer_one: {...},
   reducer_two: {...},
   reducer_three: {...}
}

I tried to reduce the array to an object with the objects’ respective foo property in order to retrieve its type but the output type of the reduce remains an empty object.

Thanks in advance for your help. Hope the description of the issue is clear enough