Cant find the bug on if statement

I am learning JS coding with A Simple Way To Learn book. On the exercises I have the below problem.

ScreenShot from the Code

I am believing that my code is correct. Only difference I notice is that my second line is not starting with tab. If I press on tab button it doesn’t work. If I leave my code as it is I am receiving the error. If I create the tab with space button also not working. If I copy the sample code and paste I am passing the question.

Can anyone tell me what I am doing wrong. Maybe something very basic but I just start learning this.

Javascript consecutive click event on same button to change css

I would like to create a click event on a check box and add a CSS class. I can use “classList.toggle” to add and remove the a CSS class by clicking the button 2 times.
This is what I would like to do. When I click the checkbox for the first, I would like to add “xyz” class and when I click the same check box, I would like to add “abc” class and remove the “xyz” class.

  const openModal = document.getElementById('mark-as-gift');
  const modalBg = document.querySelector('.addtnew');
  
  openModal.addEventListener('click', openModalBtn);
 
  function openModalBtn() {
     modalBg.classList.add('menscart2');
      
  }

Here is my startet JS code. Thanks for the help

My terminal is reading webpack compiled successfully but browser page is empty after connecting to react-dom

Here is my app.js

import Home from "./pages/home/Home";
import Login from "./pages/login/Login";
import Profile from "./pages/profile/Profile";
import Register from "./pages/register/Register";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/">
          <Home />
        </Route>
        <Route path="/login">
          <Login />
        </Route>
        <Route path="/register">
          <Register />
        </Route>
        <Route path="/profile">
          <Profile />
        </Route>
      </Routes>
    </Router>
  );
}

export default App;

and here is my index.js (connections)

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

and the versions of react, react dom etc are mentioned below

{
  "name": "ft-app-four",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.12.4",
    "@material-ui/icons": "^4.11.3",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "^5.0.1",
    "web-vitals": "^2.1.4"
  }

The terminal says You can now view ft-app-four in the browser.

Local: http://localhost:3000
On Your Network: http://192.168.42.136:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully

but I am unable to view anything on the browser screen

Uncaught ReferenceError: is not defined. One of the two functions in the same js file not working [closed]

I got two functions in a .js file.
one of them can be called as expected, while the other one returns an error message:
“Uncaught ReferenceError: is not defined.”
I even tried to comment out all other script other than the function checkAvailability(), it also not working.
Please help.
Here is my HTML code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <script src="./JavaScript/indexScript.js"></script>
    <link rel="stylesheet" href="./CSS/indexStyle.css">
</head>

<body onload="checkAvailavility(C01)">
    <div id="carDisplay">
        
    </div>

</body>
</html>

the code in the .js file:

function fetchCarDataForDisplay(){
    console.log("function 1 works")
}

function checkAvailability(carIDArg){
    console.log(carIDArg)
}

API call not working despite server returning data

I am trying to make a simple API call using Node.js as backend and React in the frontend. The status code is 200 but I am unable to view the data fetched.
My Node.js file is returning data in JSON but when I try to fetch that data I am facing this error.
Where exactly am I going wrong?

Error msg:

react-dom.development.js:14757 Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    at throwOnInvalidObjectType (react-dom.development.js:14757:1)

Code used on backend:

const http = require("http");
let user={"name":"Leo"};
var server = http.createServer(function(req ,res){
    res.writeHead(200, {'Content-Type': JSON});
    res.write(user.name,function(){
        res.write("failed");
    });   
    res.end(" done");
});
server.listen(8000);

Code on frontend(React):

function fetcher(){
        fetch("https://localhost:8000",{
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
           }
    
        })
        .then((data)=>{return data.json()})
        .then((data)=>{console.log(data)})
        .catch((err)=>{console.log(err)})
      };

while using continue keyword i got this error Uncaught SyntaxError: Unexpected token ‘else’

const mark = [
    "Mark Miller",
    78,
    1.69,
    37,
    true,
];   

for (let i = 0; i < mark.length; i++) {
        if (typeof mark[i] === "string") continue; {
            console.log(mark[i]);
        }else {
            console.log(`${mark[i]} was skipped due to continue keyword`);
        }
    }

When i remove the continue the keyword it works fine. the reason i used else block was, i wanted else to catch the skipped part; in this case “Mark Miller”.
But its showing the error “Uncaught SyntaxError: Unexpected token ‘else'”

Error: already ended, I created a list of pdf paths and tried to merge them in one file, but I’m getting Unhandled promise Error: already ended

I created a list of pdf paths and tried to merge them in one file, but I’m getting
Unhandled promise Error: already ended

this is my code, I tried also to await while adding to pdf but didn’t like it
Is there any way to handle this error?

 listOFPdf.push(docPath.filepath);//list of pdf paths
    const merger = new PDFMerger();
    (async()=>{
      listOFPdf.forEach(file=> { //loop through paths and merge them
      const mergedPdf = await merger.save(file); // save the path
    })
  }) ();// calling the function

How to call GET Api with input param use JQuery and JavaScript in Asp.net view when a special tag load

Hi I want to load count of orders in my view (in a special tag), I wrote a SP in Sql which return count of order according to input type. I design several box in my form to show all types order count.
So I give “Id” to my tag and I want when form loads, this tag show the number.
I wrote a script at the bottom of my view.
View and script and controller :

     <div class="inner">
            <h3 id="Orders1"><sup style="font-size: 20px"></sup></h3>
            <p>New Orders </p>
     </div>

<script>
    $("#Orders1").load(
    function () {
        $.ajax({
            url: '/Report/GetResultTestData',
            data: JSON.stringify({
                id: 1 /// input value 
            }),
            type: 'GET',
            contentType: 'application/json; charset=utf-8'
        }); 
   </script>

And My controller is like bellow :

    [HttpGet]
    public IActionResult GetResultTestData(int id )
    {
        var data = _sv.GetResultTestData(id);

        return new JsonResult(data);
    }

but unfortunately it doesn’t show anything would you please guide me!

OctoberCMS – How to generate JSON file from database

I’ve created OctoberCMS plugin similar to blog plugin but display my previous and upcoming projects and want to use skeleton content loading feature. I googled the techniques and one of the technique resolve around generating JSON file somewhere and fetch that file onto the page?

I am still learning the ropes and want see how can I generate JSON file by capture project poster image, title and date from the database. Secondly Javascript and CSS to create the content loader effect?

Or is there better solution to give user the impression that the project items is loading into the viewport? Any code example or direction would be great.

Efficient Way of Filtering Array and Mapping in ES6

I wanted to get array that have status of “Existing” only and don’t add the status in the newArray. What is the most efficient way of doing this?

const products = [
    {
        "id": "111",
        "name": "grapes",
        "status": "Linked",
    },
    {
        "id": "222",
        "name": "banana",
        "status": "Existing",
    },
    {
        "id": "333",
        "name": "mango",
        "status": "Existing",
    },
    {
      "id": "444",
      "name": "salad",
      "status": "Linked",
      
    },
    {
        "id": "555",
        "name": "juice",
        "status": "Existing",
    }
]

  const newArray = 
    products?.map(({ name = '', id = '' }) => ({
      name,
      id,
    }))

discord.js – Sending an Embed – TypeError: Cannot read properties of undefined (reading ‘execute’)

I’m bashing my skull on the table trying to figure this out. Would love some help or suggestions if anyone has any. I’m currently just trying to push out a very simple test embed but am having 0 luck. I’m pretty new to JS and very new to the discord API. Any pros out there willing to help me out would be super appreciated!

This is the main “bot.js” script

const Discord = require('discord.js');

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

const prefix = '~';

const fs = require('fs');

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('QQ is Online!');
});

//these require a ~ prefix

client.on('messageCreate', messageCreate => {
    if(!messageCreate.content.startsWith(prefix) || messageCreate.author.bot) return;
    
    const args = messageCreate.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();
    
    if(command === 'ping'){
        client.commands.get('ping').execute(messageCreate, args);
    }
    
    else if(command === 'stoplight'){
        client.commands.get('stoplight').execute(messageCreate, args, Discord);
    }
}); 

And this is the super simple test embed I’m trying to push out.

module.exports = {
    name: 'test name',
    description: 'test desc',
    
    execute(messageCreate, args, Discord) {
    
        const Embed = new Discord.MessageEmbed()
            .setColor('#0099ff')
            .setTitle('Test Title')
            .setDescirption('Test desc.');
    
        channel.send(Embed);
    
    }
}

And finally, this is the error I keep getting…

C:UsersCueQDesktopDiscord Botbot.js:34
                client.commands.get('stoplight').execute(messageCreate, args, Discord);
                                                ^

TypeError: Cannot read properties of undefined (reading 'execute')
    at Client.<anonymous> (C:UsersCueQDesktopDiscord Botbot.js:34:35)
    at Client.emit (node:events:539:35)
    at MessageCreateAction.handle (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jssrcclientactionsMessageCreate.js:26:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jssrcclientwebsockethandlersMESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:351:31)
    at WebSocketShard.onPacket (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:301:10)
    at WebSocket.onMessage (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jsnode_moduleswslibevent-target.js:199:18)
    at WebSocket.emit (node:events:527:28)
    at Receiver.receiverOnMessage (C:UsersCueQDesktopDiscord Botnode_modulesdiscord.jsnode_moduleswslibwebsocket.js:1160:20)

Thanks in advance~

JS onChange event is triggered when input element is clicked or in focus

I have many onChange events in my react app. These onChange events should only be triggered when there is a change in value.

But, the onChange event is triggered when I click on input and it comes to focus. There is a separate onFocus event for this then why is this happening?

I tried this in a code sandbox with just an input element and onChange event and faced the same problem.