Unexpected if else behaviour

I am working on a website which is constructed on mvc framework.
The problem isn’t related to mvc or web development but rather I feel it is a general programming issue. So I have a if and else block which is behaving unexpectedly.

Code:

class table {
    constructor(datatypes, header, data, customfunctionsindex, customfunctionstype, customfunctions) {
        this.datatypes = datatypes;
        this.header = header;
        this.data = data;
        this.customfunctions = customfunctions;
        this.customfunctionsindex = customfunctionsindex;
        this.customfunctionstype = customfunctionstype;

    }
}
var data= new table(["label", "label", "input", "input", "input", "label","select", "button"],
    ["Saletype", "Service", "Quantity", "Discount", "GST", "Amount", "Employee", "Remove"], [],
    [2, 3, 4, 6], [function () {}, "null", "null", "null"],
    ["onchange", "onchange", "onchange", "onclick"]);

            for (var i = 0; i < data.header.length; i++) {
            var cell = row.insertCell(i);
            var element = document.createElement(data.datatypes[i]);
            element.id = data.header[i] + (table.rows.length - 1);
            if (data.datatypes[i] == "label") {
                console.log(data.datatypes[i]+i);
                element.innerHTML = data.data[i];
                element.style.backgroundColor = "rgb(134 198 244)";
                element.style.color = "white";
                element.style.borderRadius = "0";
            }
            if (data.datatypes[i] == "input") {
                console.log(data.datatypes[i]+i);
                element.value = data.data[i];
                element.style.backgroundColor = "rgb(134 198 244)";
                element.style.color = "white";
                element.style.borderRadius = "0";
            }
            if (data.datatypes[i] =="select")
            {
                console.log(data.datatypes[i]+i);
                for (var i = 0; i < employees.length; i++) {
                    var option = document.createElement("option");
                    option.text = employees[i].name;
                    option.value = employees[i].name;
                    element.appendChild(option);
                }
                element.style.backgroundColor = "black";
                element.style.borderRadius = "10px";
                element.style.color = "white";
            }
            else {
                console.log(data.datatypes[i]+i);
                element.innerHTML = data.data[i];
                element.style.backgroundColor = "red";
                element.style.color = "black";
                element.style.borderRadius = "0";

            }}

Output in Console

Avoid duplication image JS

How to avoid duplication photo while displaying random photos each time?

let photosList = [
    './images/1.jpg',
    './images/2.jpg',
    './images/3.jpg',
    './images/4.jpg',
    './images/5.jpg',
    './images/6.jpg'
];

function RandomIndex() {
    return Math.floor(Math.random() * photosList.length);
}

function showList() {
    document.querySelectorAll('.classImg').forEach(function(tag) {
        let index = RandomIndex();
        tag.src = photosList[index];
    })
}

showList();

Send post petition to dB.json

I’m new here and also in web development, I have a github repository with a “db.json” file which I use with json-server, my question is how can I make “post” requests outside of json-server, Do I have to host the .json somewhere?

How does changing an image src when the user clicks on it work?

I’m trying to create a simple code where if the user clicks on the gif, it’ll switch to another gif repeatedly until it reaches the end of the loop, where the loop restarts. This is the relevant chunk of code:

var storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif
var onGifClick = function(){
    if (document.getElementById("coloredGif").src === "/images/green.gif"){
        document.getElementById("coloredGif").src = "/images/blue.gif";

    } else if (document.getElementById("coloredGif").src == "/images/blue.gif"){
        document.getElementById("coloredGif").src = "/images/yellow.gif";

    } else if (document.getElementById("coloredGif").src == "/images/yellow.gif"){
        document.getElementById("coloredGif").src = "/images/red.gif";

    } else if (document.getElementById("coloredGif").src == "/images/red.gif"){
        document.getElementById("coloredGif").src = "/images/green.gif";
    }}
storedColoredGif.addEventListener("click", onGifClick);

It’s very straightfoward. All of the path names are correct and the gifs source is initially green. The program stores the gif in a variable, then in the function it checks for what the source of the gif is and changes it accordingly when the user clicks on the gif. But nothing happens when I click on it. Am I doing something wrong in my loops? If I had to guess, the problem is that I am correctly changing the source, its just that im never updating the html (but refreshing the page would set the gif to green again because thats what i set in the main html body). What am I doing wrong?

This is how the gif is put in the html (the green.gif is shown fine, its just that its not switching between the gifs when clicked)

    <img src="/images/green.gif" id="coloredGif" title="Click me!">

When getting variable from router it returns requestProvider.js.map in node.js

I have a node.js app. When the webpage is rendered the first time all works as expected, but when inspecting the app crashes, and the req.params.slug shows as requestProvider.js.map.

router.get('/:slug', async (req, res) => {
  const article = await Article.findOne({ slug: req.params.slug })
  if (article == null){
    res.render('/')
  } 
  res.render('articles/show', { article: article })
})

Edit
With Console.Log Messages

router.get('/:slug', async (req, res) => {
  console.log("slug")
  console.log(req.params)
  const article = await Article.findOne({ slug: req.params.slug })
  console.log("article")
  console.log(article)
  if (article == null){
    res.render('/')
  } 
  console.log("article")
  console.log(article)
  console.log("title")
  console.log(article.title)
  res.render('articles/show', { article: article })
})

The console messages are

slug
{ slug: ‘requestProvider.js.map’ }
article
null
article
null
title
C:UserssamueOneDriveDesktopshortcuts and unusedUnused 2Blogpublicroutesarticles.js:32
console.log(article.title)
^

TypeError: Cannot read properties of null (reading ‘title’)
at C:UserssamueOneDriveDesktopshortcuts and unusedUnused 2Blogpublicroutesarticles.js:32:23
at processTicksAndRejections (node:internal/process/task_queues:96:5)
[nodemon] app crashed – waiting for file changes before starting…

Is it possible to create nested elements in javascript using documentFragment?

I would like to create a reuseable html block using documentFragment. The idea is to create and fill a block of html code similar to below, for every object in an existing array. I’m not worried about filling the inner html yet, for now I just want to build a nested hierarchy.

<div class="container">
    <div class="titleABC">
        <h2 class="abc"></h2>
        <h2 class="efg"></h2>
        <h2 class="xyz"></h2>
        ...
        ...
        ...
        ...
    </div>
</div>

I’ve add the code I was working on to a js Fiddle.

I could not get more than one element to work in the document Fragment and was wondering if this is possible. Or if there is a better way to accomplish this, a steer in the right direction would be appreciated.

Ultimately I want to be able to add code like…
line 16, 17, 18, 19 in my js fiddle, and have a code block generated simply from having added it to the array.

Thank you in advance for time you waste helping me with my nonsense.

Node JS MSQL cannot read property ‘length’ of undefined

i wanna add user to my database but I got this error when I add results.length:

(node:12124) UnhandledPromiseRejectionWarning: TypeError: Cannot read property ‘length’ of undefined

This is the code:

const mysql = require('mysql')
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

exports.register = (req, res) => {
    console.log(req.body);

    const { name, email, password, passwordConfirm } = req.body;

    db.query('SELECT email FROM users WHERE email = ?', [email], async (error, results) => {
        if (error) {
            console.log(error);
        }

        if (results.length > 0) {
            return res.render('register', {
                message: 'That email is already in use'
            })
        } else if (password !== passwordConfirm) {
            return res.render('register', {
                message: 'Passwords do not match'
            });
        }

        let hashedPassword = await bcrypt.hash(password, 8);
        console.log(hashedPassword);
    });
}

How to convert this arrow function to a normal function?

This is from a child component in Vue.js. I’m trying to pass some data from the parent in sensorData, but the binding isn’t happening because the code below uses an arrow function for data. How can I convert this function to a normal function so that the this binding is available.

export default {
  name: "SensorChart",
  props: ["sensorData"],

  data: () => ({
    chartOptionsLine: {
      xAxis: {
        data: ["A","B","C","D","E","F","G"]
      },
      yAxis: {
        type: "value"
      },

      series: [
        {
          type: "line",
          // data: this.sensorData
          data: [910, 423, 61, 752, 262, 3625, 119]
        }
      ],
      title: {
        text: "Sample Data",
        x: "center",
        textStyle: {
          fontSize: 20
        }
      },
      color: ["#1271c2"]
    }
  })
};

React Route – When changing pages, page loses styling

So when I switch to a page with React router it has no styling atleast up until I refresh it…
so we are on the “/” page, which is the home page and this has styling etc.
enter image description here

now I will switch to the /problemSubmission page

enter image description here

Now if I refresh, it’s going to be back to normal and fine.

enter image description here

Here’s a snippet of my code.
I am aware of using for react router aswell and that seemed to have the same problem.

import * as React from "react";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import AccountCircle from "@mui/icons-material/AccountCircle";
import MenuItem from "@mui/material/MenuItem";
import Menu from "@mui/material/Menu";
import { bgcolor } from "@mui/system";
import { Link, useNavigate } from "react-router-dom";

export default function MenuAppBar() {
  const navigate = useNavigate();

  const [auth, setAuth] = React.useState(true);
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleChange = (event) => {
    setAuth(event.target.checked);
  };

  const handleMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = (path) => {
    navigate(path);
    setAnchorEl(null);
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <AppBar
        sx={{
          bgcolor: "brown",
          borderBottom: "3px solid #eceff1",
          padding: "0 px",
        }}
        position="absolute"
        elevation={0}
      >
        <Toolbar variant="dense">
          <IconButton
            size="large"
            edge="start"
            color="inherit"
            aria-label="menu"
            sx={{ mr: 2, color: "black" }}
          >
            <MenuIcon />
          </IconButton>
          {auth && (
            <div>
              <IconButton
                size="large"
                aria-label="account of current user"
                aria-controls="menu-appbar"
                aria-haspopup="true"
                onClick={handleMenu}
                color="inherit"
                sx={{ flexGrow: 1, color: "black" }}
              >
                <AccountCircle />
              </IconButton>
              <Menu
                id="menu-appbar"
                anchorEl={anchorEl}
                anchorOrigin={{
                  vertical: "top",
                  horizontal: "right",
                }}
                keepMounted
                transformOrigin={{
                  vertical: "top",
                  horizontal: "right",
                }}
                open={Boolean(anchorEl)}
                onClose={handleClose}
              >
                <MenuItem onClick={() => handleClose("/")}>Home</MenuItem>
                <MenuItem onClick={() => handleClose("/problemSubmission")}>Submit a problem</MenuItem>
              </Menu>
            </div>
          )}
        </Toolbar>
      </AppBar>
      <Toolbar />
    </Box>
  );
}

tabindex does not work with html5 and php5? [closed]

حذف

تاريخ الإنشاء

الوصف

مستأذن

الفارق

ساعات الحضور

وقت الخروج

وقت الدخول

إستئذان

الحالة

ساعات العمل

الأسم

عدد

Publish

لايوجد

لايوجد

لايوجد

لايوجد

لايوجد

لايوجد

لايوجد

لايوجد

لايوجد

How to place Local Storage on to the DOM – JavaScript

My problem I am having is when I loop through my local storage only the last item get place on the DOM when I want to place all items to do the DOM

function checkStorage() {
  let cartContents = document.getElementsByClassName("products")[0];
  let cartProduct = document.createElement("div");
  cartProduct.classList.add("product");
  let cartCheck = JSON.parse(localStorage.getItem("localItem"));
  // return cartCheck;
  savedCart = "";
  if (cartCheck === null) {
    return;
  } else {
    console.log(cartCheck);
    for (const check in cartCheck) {
      if (Object.hasOwnProperty.call(cartCheck, check)) {
        const element = cartCheck[check];
        savedCart = `<img width="60" src="${element.img}" alt="iphone" />
                    <div>
                      <span class='title'> ${element.title}</span>
                      <div class='price-section'>
                      <input type="number" value="1" class="cart-quantity-input" />
                      <span class='cart-price'>${element.price}</span>
                      </div>
                  
                    </div>
                    <button class='btn-danger'>
                      <i class="bi bi-x"></i>
                    </button>`;
        cartProduct.innerHTML = savedCart;
        console.log(cartProduct);
        cartContents.append(cartProduct);
      }
    }
  }
}

Set class for only one button at a time in MaterialUI table row

I’m using Material UI with TypeScript in React. When a user clicks the button, I want the button to be highlighted. Currently, this code will change the buttons color, but when I click another button, that also gets highlighted. I’m trying to only have one button highlighted at a time so when I click a different button, I want the previous button to be set to the regular class and the new button to be set to the clicked class. If I click the button again, it will remove the class, but I only want the “clicked” class to only be the current button. I’ve seen this done with indexes, but am wondering what the best way to approach this would be. Any help is appreciated.

I’m currently styling the clicked class in index.css to override material-ui themes:

index.css

.btnClass.clicked {
    background-color: #1976D2;
    color: #FFFFFF;
}
// ...
                <TableBody>
                    {state.currentUsers
                        .slice(
                            page * rowsPerPage,
                            page * rowsPerPage + rowsPerPage
                        )
                        .map((users) => {
                            return (
                                <SelectUser
                                    key={Number(user.uid)}
                                    name={user.name}
                                />
                            );
                        })}
                </TableBody>
import React, { useState } from "react";

import Button from "@material-ui/core/Button";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";

import { useStyles } from "./useStyles";


export function SelectUser(props) {
    const classes = useStyles();

    const [btnClass, setBtnClass] = useState(false);

    return (
        <TableRow className={classes.tableRow} key={props.uid}>
            <TableCell component="th" scope="row" align="left">
             // when button is clicked, set current button to clicked class and all other buttons to unclicked 
                <Button 
                    className={btnClass ? "btnClass clicked" : "btnClass"}
                    onClick={() => {
                        props.setUser(props.user);
                        btnClass ? setBtnClass(false) : setBtnClass(true); // set previous button to unclicked
                    }}
                >
                    { props.id}
                </Button>
            </TableCell>

            <TableCell component="th" scope="row" align="right">
                {props.name}
            </TableCell>
        </TableRow>
    );
}

How to fix error (cant access lexical declaration Array before initialization ) in react.js?

I set the array in onchange method and I see it in the console with console.log(“array =”,array)
with all elemets but when I want to delete the duplicate element with Array.from(new Set(array)) method in the update method
, I find error in the console ( cant access lexical declaration Array before initialization ) !

const [array, setArray] = useState([]); 

const update = (e) =>{ 

  e.preventDefault();  console.log("array =",array);  // = [ 1,  1, 2, 2, 51, 51 ] 
  
  if( array !==undefined){ 
  
    const Array = Array.from(new Set(array));    // error   } }
    
    setarticlesolde((pre) => {      
      pre[artItem.articleId+1]= e.target.value;
      setArray((pre) => [...pre,artItem.articleId]);
      return  [... pre];
    })

app don´t update useEffect Socket.io/react

i have a problem whit a simple chat app, when i send a message in the other clients don´t see the update, this is the backend

const express = require('express')
const cors = require('cors')
const http = require('http')
const {Server} = require('socket.io')

const app = express()
app.use(cors())

const server = http.createServer(app)
const io = new Server(server,{cors:'http://localhost:3000'})

let mensaje

io.on('connection',socket =>{
    socket.on('new',data =>{
        mensaje = data
        socket.emit('mensaje',mensaje)
    })
})

server.listen(3001,() =>{
    console.log('Server online')
})

and de frontend

import {io} from 'socket.io-client'
import {useState, useEffect} from 'react'

const socket = io('http://localhost:3001')


function App() {
  const [user,set_user] = useState('')
  const [mensaje,set_mensaje] = useState('')
  const [mensajes,set_mensajes] = useState('')

  const handle_input = ({target}) =>{
    set_user(target.value)
  }
  const handle_message = ({target}) =>{
    set_mensaje(target.value)
  }
  const handle_click = () => {
    socket.emit('new',{user,mensaje})
  }

  useEffect(() => {
    socket.on('mensaje',data =>{
      set_mensajes(data)
    })
  }, [socket])

  return (
    <main>
      <div>
        <h1>Hi {user}</h1>
        <input type="text" onChange={handle_input}/>
        <h2>what do u want to say today</h2>
        <input type="text" onChange={handle_message}/>
        <button onClick={handle_click}>Send</button>
      </div>
      <div>
        <h1>{mensajes.user}</h1>
        <p>{mensajes.mensaje}</p>
        <br/>
      </div>
    </main>
  )
}

export default App;

they are the version from all

“express”: “^4.17.3”,
“socket.io”: “^4.4.1”,
“react”: “^18.0.0”,
“socket.io-client”: “^4.4.1”,

i found if add

...
socket.emit('mensaje',mensaje)
socket.broadcast.emit('mensaje',mensaje)

in the backend works well, but i khow that is´nt the correct way to do it

Splitting an array with N arrays of a value pair, into set N sets

Any help or suggestion on how to achieve please?

I have a group of 8 teams

    teamArray  =['Team_1', 'Team_2', 'Team_3', 'Team_4', 'Team_5', 'Team_6', 'Team_7', 'Team_8']

and use the following function to pair each team which give 28 pairs

    let pairs = teamArray.flatMap(
        (v, i) => teamArray.slice(i+1).map( w => [v,w] )
    );

Now I want to take the 28 pairs and split into 7 arrays of with 4 pairs, while each array cannot have an pair with one value more than once?

an example of the desired output:

result  = [
[['Team_1', 'Team_2'], ['Team_3', 'Team_4'], ['Team_5', 'Team_6'], ['Team_7', 'Team_8']],
[['Team_1', 'Team_3'], ['Team_2', 'Team_4'], ['Team_5', 'Team_7'], ['Team_6', 'Team_8']],
...]