Remove element class with a matching id of radio button if unchecked

I’ve been trying to find an answer but it isn’t giving me any answers and all I found is for checkboxes I tried this but .removeClass doesn’t work plus I have to copy and paste every single thing. I know there’s a more compact way how do it but i don’t know how to

$("#group1").change(function() {
  if ($(this).is(":checked")) {
    $(".group1").addClass("red");
  } else {
    $(".group2").removeClass("orange");
  }
});

$("#group2").change(function() {
  if ($(this).is(":checked")) {
    $(".group2").addClass("orange");
  } else {
    $(".group2").removeClass("orange");
  }
});
div {
  width: 100px;
  height: 100px;
  border: 1px solid
}

.red {
  background-color: red
}

.orange {
  background-color: orange
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="radio" name="numbers" value="first" id="group1" />
<label for="id1">1</label>

<input type="radio" name="numbers" value="second" id="group2" />
<label for="id2">2</label>

<div class="group1"></div>
<div class="group2"></div>

undefined is appending in top of documnet

Trying to create a page using Javascript. when I try to append HTML into the main div I can see the HTML but I’m seeing undefined in the first line of the document.

const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' }
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  let html;
  return (html += `<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype} 
                          </li>
                      </ul>
                  </div`);
})```


All I'm trying to do is create a list item, I don't have any console logs in the file or browser.


can someone please help to understand why I'm seeing undefined in the top line? 

[code snippet](https://stackblitz.com/edit/js-jfz9dk?file=index.js)

How do I get the answers on the table using vanilla JS?

I am trying to get the answers in the table and am unsure how to do so using only Javascript. No JQuery
https://jsfiddle.net/4yxz39gk/

const grid=document.querySelector(".grid")
const smallgrid=document.querySelector(".grid-small")
let num = []
let times= []

function arr(){
    for (let i=0; i<169; i++){
       let small=document.createElement("div")
       grid.appendChild(small)
       num.push(small)
       
        num[i].classList.add("grid-small")
      
      
      
    }
       
     
    
}

arr()


function time(){
    for(let i=1; i<13; i++){
        for(let j=1; j<13; j++){
            let result = i*j
            times.push(result)
            
        }
    }
}
time()
console.log(times)

How do I add my answers to my table!
Any help is much appreciated.

Thanks

How can mongodb generate unique key in embeded document

I want to add a new address to the following document

{
    username: abcd,
    password: xyz,
    addressList: {
        key1: {
            addressLine1: "12th Street",
            addressLine2: "Park Road",
            City: "Kent"
        },
        key2: {
            addressLine1: "12th Street",
            addressLine2: "Park Road",
            City: "Kent"
        }
    }
}

Can I add a new address without specifying the key and let MongoDB generate a unique one itself?

Including a contact form in the WordPress dashboard

I am currently setting up a WordPress dashboard for my clients and I am having some troubles about making the contact form work in the Dashboard. It looks like the Dashboard cannot load the Javascript from the form.

I am using White Label CMS to have an Elementor page as the Welcome Dashboard page. I have included a WPForms form in this Elementor page.

I hope someone can help me about that !

I want to change the HTML dynamically using java script after submitting form to PHP

THis My PHP code

<?php


//Include libraries
require __DIR__ . '/vendor/autoload.php';
    
//Create instance of MongoDB client
$mongoClient = (new MongoDBClient);

//Select a database
$db = $mongoClient->EcommerceWeb;

//Select a collection 
$collection = $db->Employees_Data;

//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);


 

$findemail = [
"email" => $email, 
"password" => $password, 
];

$cursor = $collection->findOne($findemail);
if($cursor){
    if($cursor['email'] == $email and $cursor['password'] == $password){ 
        echo("<script>alert('User Successfully Added')</script>");
        echo("<script>window.location = 'cms-view-products.html'</script>");
    }
}
else {
    echo("<script> alert('failed login') </script>");
    echo("<script>  window.location = 'login.html'</script>");  
}

  ?>

AND this is my HTML code

<?php include('login.php') ?>
<!DOCTYPE html>


<html>
    <head>
        <title>LogIn Demo</title>
    </head>
  
    <body>
        <form action="login.php"  method="post" >
            Email: <input type="email" name="email" required >
            Password: <input type="password" name="password" required >
            <input type="submit">
           <p id="feedback"></p>  
        </form>

</body>
    
  
</html>

What I want to do and what I have tried

I have tried to echo the massage by echoing JS code to change the innerHTML element

but didn’t work.

I tried to echo the massage using PHP which works for me but I can’t use echo then header to redirect to a different page in PHP, and I found something the $Session to solve the problem.

My question
Is there a way to use JS better than alert to produce a massage then redirect to another page in successful login OR stay on the same page if the login failed?

React ) How to access specific object in the list for save the useState

https://codesandbox.io/s/warehouse-shop-managing-system-5w9b3?file=/src/App.js

I’m making a dialog that automatically stores the inventory of the warehouse.

{
  "area1": {
    "warehouse": [
      { "type": "coffee", "quantity": "1000" },
      { "type": "beef", "quantity": "200" },
      { "type": "sugar", "quantity": "750" }
    ],
    "shop": [
      { "type": "coffee", "quantity": "15" },
      { "type": "beef", "quantity": "3" },
      { "type": "sugar", "quantity": "90" }
    ]
  }
}

Q1) There are two objects in the list. How can I store it in the list sequentially using forEach, map, etc?

(ReactHooks or ClassComponent)

  function autoLoad() {
    db.area1.warehouse.forEach(
      (item) => {
        setInputType(...inputType, item.type);
        setInputQuantity(...inputQuantity, item.quantity);
      },
      setItemList([
        ...itemList,
        {
          itemType: "warehouse",
          itemId: Date.now()
        }
      ])
    );
  }

Q2) I want to delete it only when I press the Hide_button and finally press the Final_Save button.

For example, you can’t see it in the dialog by pressing the DELETE button, but if you press the cancel button, it won’t be deleted. And if you open the dialog again, you can see the added items.

Is it right to make a separate list for deletion and a list for hiding?
or using Callback?

 const renderItemList = itemList.length
    ? itemList.map((item) => {
        return (
          <>
            <div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputType}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputQuantity}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>

              <div>{hideButton(item)}</div>
            </div>
          </>
        );
      })
    : "";

  function hideButton(item) {
    return (
      <Button
        onClick={() => removeItemInList(item.itemId)}
        style={{
          backgroundColor: "#2db7e2",
          fontSize: "14px",
          marginBottom: "30px"
        }}
      >
        {"Hide_Item"}
      </Button>
    );
  }
  const removeItemInList = (itemId) => {
    setItemList(
      itemList.filter((item) => {
        return item.itemId !== itemId;
      })
    );
  };
import "./styles.css";
import {
  TextField,
  Tooltip,
  MuiButton,
  Button,
  Dialog,
  DialogContent,
  DialogActions
} from "@material-ui/core";
import React, { useState, useRef, useEffect } from "react";
import { Map, List } from "immutable";
import db from "./db.json";

export default function App() {
  const [showDialog, setShowDialog] = useState(false);
  const [inputType, setInputType] = useState("");
  const [inputQuantity, setInputQuantity] = useState("");
  const [itemList, setItemList] = useState([]);
  const [jsonData, setJsonData] = useState({});

  useEffect(() => {
    setJsonData(db);
    autoLoad();
    console.log("itemList:", itemList);
  }, []);

  function autoLoad() {
    db.area1.warehouse.forEach(
      (item) => {
        setInputType(...inputType, item.type);
        setInputQuantity(...inputQuantity, item.quantity);
      },
      setItemList([
        ...itemList,
        {
          itemType: "warehouse",
          itemId: Date.now()
        }
      ])
    );
  }

  function resetForm() {
    setInputType("");
    setInputQuantity("");
  }

  function addList(e) {
    e.preventDefault();
    setItemList([
      ...itemList,
      {
        itemType: "shop",
        itemId: Date.now(),
        inputType: inputType,
        inputQuantity: inputQuantity
      }
    ]);
    resetForm();
  }

  const renderItemList = itemList.length
    ? itemList.map((item) => {
        return (
          <>
            <div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputType}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>
              <div style={{ height: "60px" }}>
                <TextField
                  value={item.inputQuantity}
                  type="text"
                  style={{ marginBottom: "30px" }}
                />
              </div>

              <div>{hideButton(item)}</div>
            </div>
          </>
        );
      })
    : "";

  function openDialog() {
    setShowDialog(!showDialog);
  }

  function onDismiss() {
    setShowDialog(false);
    setInputType("");
    setInputQuantity("");
  }

  const removeItemInList = (itemId) => {
    setItemList(
      itemList.filter((item) => {
        return item.itemId !== itemId;
      })
    );
  };

  function hideButton(item) {
    return (
      <Button
        onClick={() => removeItemInList(item.itemId)}
        style={{
          backgroundColor: "#2db7e2",
          fontSize: "14px",
          marginBottom: "30px"
        }}
      >
        {"Hide_Item"}
      </Button>
    );
  }

  function onSubmit() {}

  return (
    <>
      <Button onClick={openDialog} style={{ backgroundColor: "#4cb7f3" }}>
        {"Here"}
      </Button>
      <Dialog open={showDialog} onClose={onDismiss}>
        <div
          className="App"
          style={{ height: "500px", width: "500px", alignItems: "center" }}
        >
          {renderItemList}
          <div style={{ height: "100px" }}>
            <TextField
              type="text"
              // value={}
              placeholder="Please, Input the Type"
              onChange={(e) => setInputType(e.target.value)}
              style={{ marginTop: "30px", marginBottom: "30px" }}
            />
          </div>
          <div style={{ height: "60px" }}>
            <TextField
              type="text"
              // value={inputQuantity}
              placeholder="Please, Input theQuantity"
              onChange={(e) => setInputQuantity(e.target.value)}
              style={{ marginBottom: "30px" }}
            />
          </div>
          <div style={{ height: "40px" }}>
            <Button
              type="submit"
              onClick={addList}
              style={{ backgroundColor: "#fc7090", fontSize: "14px" }}
            >
              {"add"}
            </Button>
            <br />
            <br />
            <Button
              type="submit"
              onClick={onSubmit}
              style={{ backgroundColor: "#80cbc4", fontSize: "14px" }}
            >
              {"final_save"}
            </Button>
          </div>
        </div>
      </Dialog>
    </>
  );
}

how to change button class when i click on it using Jquery?

so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can’t find a way to do it

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
      });
    });
  </script>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button id="p" class="btn btn-success">Random button</button>
  </body>
</html>

I get this error: Cannot read properties of undefined (reading ‘send’) when I run the command I made, What do I do?

So I am trying to make an embed rules message for my server and I get an error saying “Cannot read properties of undefined (reading ‘send’)”.

The code:

const message = require("../events/guild/message")
const { MessageEmbed } = require('discord.js')

module.exports = {
    name: 'spawnrules',
    description: "Spawn the server rules",
    execute(message, args, Discord, client) {
        const rules = new MessageEmbed()
        .setColor('LIME')
        .setTitle('Rules')
        .setDescription('These are the server rules, Make sure to follow them to avoid being punished.')
        .addFields(
            {name: '1'},
            {name: 'Do not be racist', value: '2'},
            {name: '2'},
            {name: '3'},
            {name: 'No NSFW', value: 'NSFW is forbidden in our server. NSFW will result in a discord report and a permanent ban.'},
        )
        .setFooter('32')
        message.channel.send(rules)
    }
}

Error:

        message.channel.send(rules)
                        ^

TypeError: Cannot read properties of undefined (reading 'send')
    at Object.execute (C:TeamsTeam LapisLapis Botcommandsspawnrules.js:20:25)
    at module.exports (C:TeamsTeam LapisLapis Boteventsguildmessage.js:9:25)
    at Client.emit (node:events:520:28)
    at MessageCreateAction.handle (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientactionsMessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsockethandlersMESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:TeamsTeam LapisLapis Botnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:301:10)
    at WebSocket.onMessage (C:TeamsTeam LapisLapis Botnode_moduleswslibevent-target.js:132:16)
    at WebSocket.emit (node:events:520:28)

I’d appreciate it if someone will help 🙂

How to make a select option dropdown with objects? Javascript and HTML

I’m trying to make a select option dropdown in javascript and write it in HTML. The options are placed in an object in javascript (under “valg”). I have tried different solutions but, I can’t get it to work properly. Do you have any ideas?

The code is here:


let produkter = [
            {
            navn: 'Eple',
            pris: 20,
            beskrivelse: 'Smakfullt og sunt.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['Grønt', 'Rødt', 'Gult'],
            antall: 0 
        },
            {
            navn: 'Banan',
            pris: 15,
            beskrivelse: 'Gult og kult.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['Små', 'Store'],
            antall: 0 
        },
            {
            navn: 'Pære',
            pris: 12,
            beskrivelse: 'Alltid en pære til lunsj.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['Små', 'Store'],
            antall: 0 
        },
            {
            navn: 'Sitron',
            pris: 14,
            beskrivelse: 'Sitron er godt.',
            bilde: '<img id="bilde" src="../bilder/iphone.jpeg">',
            valg: ['Moden', 'Ikke moden'],
            antall: 0 
        }
        ]

        
        
        for (var i = 0; i < produkter.length; i++) {
            let bodyEl = document.querySelector("body");
            bodyEl.id = "bodydiv";
            let hovedEl = document.createElement("div");
            hovedEl.id = "hoved";
            bodyEl.appendChild(hovedEl);



            let h2El = document.createElement("h2");
            h2El.id = "navn"
            h2El.innerHTML = produkter[i].navn;
            hovedEl.appendChild(h2El);

            let bildeEl = document.createElement("p");
            bildeEl.innerHTML = produkter[i].bilde;
            hovedEl.appendChild(bildeEl);

            let avsnittEl = document.createElement("p");
            avsnittEl.id = "beskrivelse";
            avsnittEl.innerHTML = produkter[i].beskrivelse;
            hovedEl.appendChild(avsnittEl);

            let prisEl = document.createElement("p");
            prisEl.innerHTML = 'kr. ' + produkter[i].pris;
            hovedEl.appendChild(prisEl);

            let antallEl = document.createElement("input");
            antallEl.type = "number";
            antallEl.id = "antall"
            hovedEl.appendChild(antallEl);

            let knappEl = document.createElement("button");
            knappEl.innerHTML = "Kjøp";
            knappEl.id = "knapp";
            hovedEl.appendChild(knappEl);
            knappEl.onclick = function() {
                alert('Knapp er trykket på');
            }


            // Here I'm trying to make the select option dropdown

            let flervalgEl = document.createElement("select");
            flervalgEl.innerHTML = produkter[i].valg;
            hovedEl.appendChild(flervalgEl);

            let valgAltEl = document.createElement("option");
            valgAltEl.innerHTML = produkter[i].valg[i];
            flervalgEl.appendChild(valgAltEl);

                    
        }

It’s the last part of the code that I’m struggling with. Under the comment.

Authenticate microsoft account to firebase website only, and not other microsoft services

I am using firebase for a website, where users can sign in with their microsoft accounts:

import {getAuth, signInWithRedirect, OAuthProvider} from "firebase/auth";

(...)

const provider = new OAuthProvider('microsoft.com');
const auth = getAuth();
signInWithRedirect(auth, provider);

I have managed to make everything work nicely, except one detail:
When I sign in with the Microsoft account in the webbrowser for the firebase site, I am also signed in to my complete Office 365 account in the background (and probably other mirosoft sites).

So if I go to the website for my Outlook 365 online mail, then I am already logged in since I logged into my firebase project.

How can I limit the microsoft sign-in to only authenticate in the firebase project, and nothing else?

ReactJs – Sort method

I have a table in my react app and it gets its data from API.

I want to sort one of its columns. a[obj1][obj2] or b[obj1][obj2] Usually is a string of numbers and sometimes are equal to "-" (Dash)
this is my sort function:

if (order === "DEF") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) > Number(b[obj1][obj2])
      ? 1
      : Number(b[obj1][obj2]) > Number(a[obj1][obj2]) || a[obj1][obj2] === "-"
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("ASC");
} else if (order === "ASC") {
  const sorted = props.currency.sort((a, b) =>
    Number(a[obj1][obj2]) < Number(b[obj1][obj2]) || a[obj1][obj2] === "-"
      ? 1
      : Number(b[obj1][obj2]) < Number(a[obj1][obj2])
      ? -1
      : 0
  );
  props.setCurrency(sorted);
  setOrder("DSC");
} else {
  const sorted = defaultCurrency;
  props.setCurrency(sorted);
  setOrder("DEF");
}

After the sort is called I want to behave with "-" like a zero,
but the items which are equal to "-"are always placed on the top of the table when the order is equal to ASC or DSC, while the other items of the array are sorted correctly.

Chart JS tick options not working for y axis

I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don’t want there.

Here is the example:

    <canvas id="lineChart"></canvas>
    <script>
        var ctx = document.getElementById('lineChart');
        var lineChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [1,2,3],
                datasets: [{
                    data: [0, 0, 0]
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        ticks: {
                            beginAtZero:true
                        }
                    }
                }
            }
        });
    </script>
<div>```

As you can see I am changing in the options the scales as suggested in the documentation [here][1] (apparently there has been a migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:
[![chart example][2]][2]

Any axis options other than the ticks work correctly. I have also tried 
Any ideas of what I might be doing wrong? 


  [1]: https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales
  [2]: https://i.stack.imgur.com/9IWmc.png

Add newline after each key, value using JSON.stringify()

I want to add a newline after each key value pair in an object using JSON.stringify()

In my actual code I will be getting a lot of key value pairs and having the new lines makes it easier to read.

Example code is:

let test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three']}

let testOne = JSON.stringify(test, null, 't')

console.log(testOne)

outputs:
{
        "key": [
                "one",
                "two",
                "three"
        ],
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

I want:
{
        "key": [
                "one",
                "two",
                "three"
        ],
                                   <----- newline here
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

I have tried

let test = {'key' : ['one', 'two', 'three'] + "\n", 'keyTwo' : ['one', 'two', 'three']+ "\n"}

let testOne = JSON.stringify(test, null, 'tn')
console.log(testOne);

Neither work