How can I add chess pieces to my code without changing much?

I basically just want to add the images of the chess pieces in the correct positon that they belong to but without changing the code very much.

//This is my Javascript code

var numbers = new Array(10);

function drawChessboard()
{


for (var row = 1; row <= 4; row++)
  { 
  
  numbers[row-1] = new Array(10);
  
  document.write("<tr>");

  for (var col = 1; col <=4; col++)
  {

    numbers [row-1][col-1] = row*col; 
    document.write("<td class='dark'></td>");
    document.write("<td class='light'></td>");
  }

  document.write("<tr>");

  for (var col = 1; col <=4; col++)
  {

    numbers [row-1][col-1] = row*col; 
    document.write("<td class='light'></td>");
    document.write("<td class='dark'></td>");
  }

  document.write("</td>")
}

}

Can’t get values of input with js

I have a inputs in loop using thymeleaf, I need when hover each iteration get the value and calculate sum

 <tr th:each="person : ${persons}">
            <td th:text="${person.first_name}"></td>
            <td th:text="${person.last_name}"></td>
            <td th:text="${person.phone}"></td>
            <td><input id="age" class="form-control"
                        type="text" name="age" th:field="*{ages}">
            </td>
    </tr>

Total : <input type="text" name="sum" id="sum"/>

My js script :

<script type="text/javascript">
    $(document).ready(function(){
          $("#age").each(function() {

            $(this).on('input', function(){
              calculateSum();
            });
            
            console.log("sum :"+sum);
          });

        });

        function calculateSum() {

          var sum = 0;
          $("#age").each(function() {
            if(!isNaN(this.value) && this.value.length!=0) {
              sum += parseFloat(this.value);
            }

          });
          $("#sum").html(sum.toFixed(2));

        }
    </script>

My code give me on total only the first value (like it doesnt work on 2nd iteration), i dont know why !!

How do I export the output of an async function?

I am running the following code. Where I am expecting to see the outputs latitude and longitude, what I get is Promise{<pending>} in my console. Why is this the case? I thought using async/await helps to eliminate the problem of pending promises since the code can’t go forward until the promise fulfills. How do I solve this problem?

const issURL = 'someUrl';
async function getData() {
            const res = await fetch(issURL);
            const data = await res.json();
            const {
                latitude,
                longitude
            } = data;
            return (latitude, longitude);
        }
console.log(getData());

fullPermissions in discord.js

I make command-handler in discord.js, but I have an error: TypeError: Cannot read properties of undefined (reading 'permissions'). If you know how to fix this, I will be very grateful, this is my code:

    client.on("ready", async () => {
    const MainGuild = await client.guilds.cache.get("890680177451995156");

    MainGuild.commands.set(CommandsArray).then(async (command) => {
        const Roles = (commandName) => {
            const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission;
            if(!cmdPerms) return null;

            return MainGuild.roles.cache.filter((r) => r.permissions.has(cmdPerms));
        }

        const fullPermissions = command.reduce((accumulator, r) => {
            const roles = Roles(r.name);
            if(!roles) return accumulator;

            const permissions = roles.reduce((a, r) => {
                return [...a, {id: r.id, type: "ROLE", permission: true}]
            }, [])

            return [...accumulator, {id: r.id, permissions}]
        }, [])

        await MainGuild.command.permissions.set({ fullPermissions });
    })
})```

WebSocket server is returning “::” for the local IP address when I call ws.address()

I am using ws with Electron for making a desktop app. I have a WebSocket server which runs in the app, but the problem is that I can’t get the IP address of that server. The IP address I’m looking for is that of the device which is listed under ipv4 of the ipconfig in CMD since I’m using Windows 11. The server.address() only returns “::” for the IP address and I need it instead saying “192.168.0.41”.

My code goes like this:

wss = new WebSocket.Server({ port: 6000 })
return wss.address() // returns "::" for address

Now on another post someone responded saying that .address() should be called after setting up the server. Well I tried it by making a new Node.js server and I got the same results for the address from the code below.

const net = require("node:net")

const s = net.createServer((socket) => {})

s.listen(() => {
    console.log("opened server on: ", s.address()) // returns "::" for address
})

Now the result I’m looking for is in the following screenshot.

How to Computed Two Results For Two Target Element in Vue.js

Can someone please let me know if there is a way to have two result() in Vue computed based on element id?
For example I want return into #and a result which is replaced comma with AND
and an other result for #dash which in this result is replaced with -

enter image description here

new Vue({
  el: '#demo',
  data() {
    return {
      target: '',
    }
  },
  computed: {
    result() {
      //if it is going to #and
      // return '`' + this.target.replaceAll(",", "` AND `") + '`' // If {{ result }} is #and
      // if it is going to #dash
      return '`' + this.target.replaceAll(",", "` - `") + '`' // If {{ result }} is #dash
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <p id="and">You Entered {{ result }}</p>
  <p id="dash">You Entered {{ result }}</p>
  <input v-model="target" placeholder="Enter Your Target" />
</div>

To do list with js disabled in the browser & no database

Pretty much what the title describes. I need to build a todo app for a job interview, but js must be disabled in the browser, and not using a database.

Any js must be done on the server side.
I have a beginner grasp on node/express and know how to serve html files, but I’m not sure how to go about updating the html files with user input without js Dom manipulation. What would be a modern approach to this problem?

Microtask Queue waits for all operations to be performed before moving to the callstack?

As far as I understood, I expected them to be printed according to the resolution time of each one (after the callstack is empty), to finally print the setTimeout() message.

However, all solutions are printed when the most time-consuming task is completed. Specifically, it is only when the promise operation of the second call to recursionSecond() is completed that all the others are also printed.

    setTimeout(() => console.log('timeout in 0'), 0);
    
    function recursionFirst(number) {
        return new Promise((resolve, reject) => {
            for(let i = 0; i > (number * (-1)); i--) {
                if(i === (number * (-1)) + 1) resolve(i)
            }
        })
    }
    
    function recursionSecond(number) {
        return new Promise((resolve, reject) => {
            for(let i = 0; i < number; i++) {
                if(i === number - 1) resolve(i)
            }
        })
    }
    
    recursionFirst(40) 
        .then(x => console.log(x))
    
    recursionFirst(400) 
        .then(x => console.log(x))
    
    recursionFirst(400) 
        .then(x => console.log(x))
    
    recursionSecond(10) 
        .then(x => console.log(x))
    
    recursionSecond(2000000000) 
        .then(x => console.log(x))
    
    recursionSecond(1000) 
        .then(x => console.log(x))
    
    console.log("Hi!")

Why after x number of times Math.random() function gives only one number over and over

I am using useState in React. After x number of time (15-20) getRandomNumbers function does not give random numbers anymore. It gives only one number over and over.

What am i doing wrong here???

import {useState} from "react";

function App() {

  const [numbers, setNumbers] = useState(['1','2','3','4', '5']);
  
  function getRandomNumbers(){
      let result = [];
      for(let i = 0; i < numbers.length; i++){
          result.push(numbers[Math.floor(Math.random() * numbers.length)]);
      }
      // setting new array in numbers
      setNumbers(numbers => result);
  }
  
  const displayNumbers = numbers.map((no, i) => {
      return (
          <div key={i}>{no}</div>
      );
  });

  return (
          <div>
              {displayNumbers}
              <br/>
              <button type='button' onClick={() => getRandomNumbers()}>Click</button>
          </div>
  );
}

export default App;

Javascript AJAX + JQuery posts emtpy data

I am new to web programming and am struggling with a basic task. I am trying to do a simple POST from my frontend to my backend and with it send data in the form of a JSON object. I specifically do not want to embed my javascript code in my HTML file. PLease note that all the code shown is all the code used for this POST purpose, so if it looks like I am missing something I most likely am. My frontend JS code is as follows:

/**/
function Test_Button_Pressed() {
    $.ajax({
        type: "POST",
        url: "/test",
        dataType: "json",
        data: {Name: "Rikus", Value: 123},
        contentType: "application/json",
        dataType: "json",
        success: function (result) {
            console.log(result);
        },
        error: function (err) {
            console.log("Error: " + err); //just use the err here
        }
    });
}

/**/
function Activation_Button_Pressed(Button_ID) {}

/**/
function Button_Pressed(Button_ID) {}

The following is logged in the Chrome console when the backend response was made:

Error: [object Object]

The backend code is as follows:

const Api = require("./Api");

var Communication = {};

/**/
Communication.SetUp = function (PanelApp, DataApp) {
    PanelApp.post('/test', (req, res) => {
        console.log(req);
        console.log(req.params);
        console.log(req.body);
        res.send("Done");
    });
};

module.exports = Communication;

Bothe the

console.log(req.body)

and

console.log(req.params)

returns: {}

so from what I can see my routing is correct, it’s only my data sending that does not work. Please help and thank you in advance.

Array methods in Javascript [closed]

Problem #1:
I have this array:

const birds = [ “Parrots”, “Falcons”, “Eagles”, “Emus”, “Caracaras”, “Egrets” ];

I’d like to create a copy of this array that includes birds that start with the letter E. How would you go about this?

Problem #2
I have this array:

let myArray = [ “Ryu”, “Ken”, “Chun-Li”, “Cammy”, “Guile”, “Sakura”, “Sagat”, “Juri” ];

How would I go through each item and add the index of the item in paranthesis? I tried using a forEach loop:

myArray.forEach((item, index) => item = item + ‘(${index})’)

But nothing happens!

Thank you.

How to copy to clipboard a selected text with styling ang images by using javascript?

When a user selects a part of the page with styled texts and images, it is possible to copy all that content (with images and styles) and paste it to MS Word or to an e-mail client by clicking “Copy” in the context menu.

How is it possible to achieve the same result with javascript?

So far, I have found solutions to copy plain text only or by using the depreciated document.execCommand("copy") command.

Is there a solution that works for all modern browsers, including Firefox?
If such a function cannot be implemented for security reasons or whatever, could someone please explain why exactly? Because users copy content all the time, why it cannot be done with Javascript?

Embed HTML Canvas script to React

So I have a Canvas Vanilla JS Tower Defence Game. I have a basic files like

game.js
game.html
game.css

I am trying to embed it to a newly created component in React. This component doesn’t have anything right now. I just need the game to be displayed in my already developed react app. Does anyone know how it can be done?

Bootstrap-select won’t drop down when clicked in ASP.NET web application

I am building an ASP.NET web application, and I am having serious trouble getting bootstrap-select to work properly.

I have looked at other posts on SO on this, and nothing seems to fix the issue, so I’m hoping I can get some help today.

The web application uses a master page, which contains the following declarations to include all of the CSS and JavaScript files:

<head runat="server">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>MCTC - <%=Page.Title%></title>
    <link href="../Content/styles.css" rel="stylesheet" /> <!-- Bootstrap CSS -->
    <link href="../Content/themes/base/jquery-ui.css" rel="stylesheet" /> <!-- jQuery-UI CSS -->
    <link href="../Content/bootstrap-select.css" rel="stylesheet" /> <!-- Bootstrap-select CSS -->
    <link href="../content/bootstrap-datepicker3.css" rel="stylesheet"/> <!-- Bootstrap-datepicker CSS -->
    <link href="../content/mctc_styles.css" rel="stylesheet" /> <!-- custom site CSS -->
    <script src="../../scripts/jquery-3.6.0.min.js"></script>
    <script src="../../scripts/bootstrap.bundle.min.js"></script>
    <script src="../../scripts/bootstrap-select.js"></script>
    <script src="../../scripts/jquery-ui-1.13.1.js"></script>
    <script src="../../scripts/bootstrap-datepicker.js"></script>
</head>

In the content page I have a bootstrap-select which is intended to display a list of product categories which are retrieved using an AJAX call. The HTML for the bootstrap-select is as follows:

        <div class="row mb-4">
            <div class="col-lg-10 offset-lg-1 text-center">
                <select class="selectpicker" id="ddlCategories" name="ddlCategories">
                    <option value="">Choose</option>
                </select>
           </div>
        </div>

At the end of the $(document).ready(function () { script section, I have the following 2 lines of code related to the bootstrap-select:

$('#ddlCategories').selectpicker();
loadCategories();

The call to loadCategories() uses the following code to make an AJAX call to retrieve a list of category records from the database. Here is that code:

        function loadCategories() {
            $.ajax({
                url: 'getcategories.ashx',
                data: null,
                method: 'post',
                dataType: 'json',
                    success: function(response) {
                        $('#ddlCategories').empty();
                        for (var i = 0; i < response.length; i++) {
                            alert(response[i].Category_ID + '='+response[i].Title);
                            $('#ddlCategories').append("<option value='" + response[i].Category_ID + ">" + response[i].Title + "</option>");
                        }
                        $('#ddlCategories').selectpicker('refresh'); // without the []
                },
                error: function (e) {
                    console.log(e.responseText);
                }
            });
        }

I included a call to an alert to ensure the data is being returned, and it is.

When I execute this code, here’s what I get on-screen:

Screenshot of result

I get no errors or messages in the console window, so I don’t know what the issue is, but clicking the bootstrap-select control does nothing – it doesn’t drop down, and it doesn’t show the data either. Whatever’s going on, it fails silently.
I thought maybe it had to do with the order I have the Javascript and CSS files loading in the master page, and I’ve followed every example I can find, but it still doesn’t seem to work.

Any help that can be provided would be GREATLY appreciated.