form validation using javascript is not working

I am working with form in HTML and, I had validated it using PHP, but I want to display an error message for the user when he/she type something and, I did it javascript.
Currently, it is not working as I want, it just stops showing messages after the first input, so any help, please?

HTML :

  <!--form-->
    <form id="form" onSubmit="return shouldISubmit()" action="updateprofile.php" method="post" >
    

             <h1>ABOUT YOU</h1>
            <?php
            

            foreach($rs as $row)
            { 
            ?>            
            <input type="hidden" name="uid" value="<?php echo $row['Uid'];?> ">
             <div class="inputwrapper">
             <label for="username">Username</label>
                         <input type="text"   id="username" name="username" value="<?php echo $row['username']; ?>" disabled />
             </div>

             <div class="inputwrapper">
                       <label  for="name">Name</label>
                     <input type="text" autocomplete="off" onKeyUp="namevalidation(this.value)"  name="uname" placeholder="<?php echo $row['name']; ?> "/>
             <span class="error" id="name_error"></span>
                    </div>

             <div class="inputwrapper">
             <label for="phone">Phone number</label>
             <input type="text"  onkeyup=" phoneValidation(this.value)"  name="phone" placeholder="<?php echo $row['phone']; ?>"/>
              <span class="error" id="phone_error"></span>
              </div>
             <div class="inputwrapper">
             <label for="email">Email </label>
             <input type="text"  onkeyup="emailAddressValidation(this.value)" name="email" placeholder="<?php echo  $row['email']; ?>">
             <span class="error" id="email_error"></span>
            </div>

             <hr>
             <h2>Address</h2>
             <div class="inputwrapper">
             <label for="city">City</label>
                     <input type="text" oninput="cityValidation(this.value)" name="city" placeholder="<?php echo $row['city']; ?>"/>
             <span class="error" id="city_error"></span>
             </div>

             <div class="inputwrapper">
                <label  for="house">House</label>
                            <input type="text"  onkeyup="houseValidation(this.value)" name="house" placeholder="<?php echo $row['House']; ?>"/> 
                <span class="error" id="house_error"></span>
              </div>

             <div class="inputwrapper">
             <label for="block">Block</label>
                            <input type="text" onkeyup="blockValidation(this.value)" name="block" placeholder="<?php echo $row['Block']; ?>" />
                  <span class="error" id="block_error"></span>
                </div>
             <div class="inputwrapper">
             <label for="road">Road</label>
                <input type="text"  onkeyup="roadValidation(this.value)" name="road" placeholder="<?php echo $row['Road']; ?>"/>                 
                <span class="error" id="road_error" ></span>
              </div>
             <br>
             <input type="hidden" name="JS" value="false" />                                                
             <?php } ?>
             <div class="btnstyle">
             <button  type="submit" class="button" name="update" value="update">Update</button></div>
                  </form>    
       <!-- end of(form)-->

Javascript:


var namevalid=emailvalid=roadvalid=blockvalid=phonevalid=cityvalid=housevalid=false;



// Email Address Validation
function emailAddressValidation(email){

 var validEmailAddress=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$/;
 document.getElementById('email_error').style.color="red";

 if(email.length==0)
 {
  document.getElementById('email_error')="Email Address is required";
  emailvalid=false;
 }else if(!validEmailAddress.test(email)){
  document.getElementById('email_error')="email is not well formated";
   emailvalid=false;
 }else{
  document.getElementById('email_error').style.color="white";
  document.getElementById('email_error')="";
  emailvalid=true;
 }
}

function namevalidation(name){

  document.getElementById('name_error').style.color="red";

 var  validName=/^[a-zA-Z-' ]*$/;   
  if(name.length==0)
  {
   document.getElementById('name_error').innerHTML="Name is required";
    namevalid=false;
  }else if(!validName.test(name)){
   document.getElementById('name_error').innerHTML=" Name must be only string with white spaces";
   namevalid=false;

 }else{
   document.getElementById('name_error').style.color="white";
   document.getElementById('name_error').innerHTML="";
   namevalid=true;
  }
}


// Phone Validation

  function phoneValidation(phone){
 var validMobileNumber=/^[36][0-9-' ]{7}$/;
 document.getElementById('phone_error').style.color="red";
 if(phone.length==0)
  {
  document.getElementById('phone_error')="Mobile Number is required";
  phonevalid=false;
 }
 else if(!validMobileNumber.test(phone)){
  document.getElementById('phone_error')="Mobile Number must be a number";
 }
 else if(phone.length!=8){
  document.getElementById('phone_error')="Mobile Number must have 8 digits";
  phonevalid=false;
 }
 else{
  document.getElementById('phone_error').style.color="white";
  document.getElementById('phone_error').innerHTML="";
  phonevalid=true;
 }

}
// city Validation

 function cityValidation(city){

 var validcity=/^[a-zA-Z-' ]*$/;

 document.getElementById('city_error').style.color="red";
 if(city.length==0)
 {
  cityvalid=false;
  document.getElementById('city_error')="City is required";
}else if(!validcity.test(city)){
  cityvalid=false;
  document.getElementById('city_error')="City must contains Only letters and white space allowed";
 }
 else{
  document.getElementById('city_error').style.color="white";
  document.getElementById('city_error')="";
  cityvalid=true;
 }
}

// house Validation

 function houseValidation (house){

 var validhouse=/^[0-9-' ]*$/;

 document.getElementById('house_error').style.color="red";

 if(house.length==0)
 {
  housevalid=false;
  document.getElementById('house_error')="house number is required";
}else if(!validhouse.test(house)){
  housevalid=false;
  document.getElementById('house_error')="House number must contains Only numbers";
 }
 else{
  document.getElementById('house_error').style.color="white";
  document.getElementById('house_error')="";
  housevalid=true;
 }
}

// road Validation
var road= document.getElementById("road");

function roadValidation(road){

 var validroad=/^[0-9-' ]*$/;
 document.getElementById('road_error').style.color="red";

 if(road.length==0)
 {
  document.getElementById('road_error')="Road number is required";
  roadvalid=false;

}else if(!validroad.test(roadValue)){
  document.getElementById('road_error')="Road number must contains Only numbers";
  roadvalid=false;

 }
 else{
  document.getElementById('road_error').style.color="white";
  document.getElementById('road_error')="";
   roadvalid=true;
 }
}


// block Validation

  function blockValidation(block){

var validblock=/^[0-9-' ]*$/;
 document.getElementById('block_error').style.color="red";

 if(block.length==0)
 {
  document.getElementById('block_error')="Block number is required";
  blockvalid=false;

}else if(!validblock.test(blockValue)){
  document.getElementById('block_error')="Block number must contains Only numbers";
  blockvalid=false;

 }
 else{
  document.getElementById('block_error').style.color="white";
  document.getElementById('block_error')="";
   blockvalid=true;
 }
}





function shouldISubmit(){
  document.forms[0].JS.value="true";
  if(namevalid && emailvalid && roadvalid && blockvalid && phonevalid && cityvalid && housevalid)
    return true;
  else
    return false;
}

Trying to create a hash table in JS… Can’t figure out how to write a “get” function with the given hash function without being given an index

So I have been able to create a set function that seems to work correctly. The problem comes when I try to create a ‘get’ function that searches the hashtable passed on a ‘key’ passed in as an argument.

The hashing function takes a ‘string’ and ‘size’ argument, not a ‘key’ like all the examples I looked at trying to figure it out. Here is the hashing function I was given…

  function hashCode(string, size){
    let hash = 0;
    if (string.length == 0) return hash;
    for (let i = 0; i < string.length; i++) {
      const letter = string.charCodeAt(i);
      hash = ((hash << 5) - hash) + letter;
      hash = hash & hash; // Convert to 32bit integer
    }
    return Math.abs(hash) % size ;
  }

Here is my ‘set’ ‘HashTable’ class function andthe ‘set’ function I wrote…

function HashTable() {
    this.SIZE = 16;
    this.storage = new Array(this.SIZE);
  }
  
  // stores a value in the storage array
  HashTable.prototype.set = function(key, value) {
    let index = hashCode(value, 16);
    if (!this.storage[index]) {
      this.storage[index] = [];
    }
    this.storage[index][key] = value
  };

I have tried a few different methods to make the ‘get’ function work. I have tried iterating through the array and using the .hasOwnProperty method and currently tried to just use dot notation in a loop to find the property (what is shown below). I can’t seem to get it to work with the methods I listed and can’t think of any other ways to find the key/value pair in the array without being able to get an index from the hashing function.

Here is the ‘get’ method I am working on…

HashTable.prototype.get = function(key) {
    this.storage.forEach((kvpair) => {
        if (kvpair.key) {
            return kvpair.key
        }
    })
  };

when I create a new instance of the class like this…

 let table = new HashTable;

and run the ‘set’ function…

table.set('key','value');

and console.log ‘table’ I get this…

HashTable {SIZE: 16, storage: [ , [ key: 'value' ], , , , , , , , , , , , , , ] }

when I attempt to run my ‘get’ method…

table.get('key')

undefined is logged to the console…

I am just unsure of how to make this ‘get’ function work without the index… I am obviously not retrieving the value correctly with my loop and dot notation…

Any tips, tricks, ideas, hints, or help will be greatly appreciated!

how to set redirect link for when user updates subscription stripe

So i have the stripe subscription portal enabled on my node.js app. It is working fine, but when someone updated there plan, it says it’s completed, but it doesn’t redirect BACK to my app unless i hit the back button. I was wondering if when they hit confirm changes, then instead of redirceting back to the portal page, go to my app instead. here’s the code i have.

    app.get('/create-customer-portal-session', authCheck, async (req, res) => {
    const session = await stripe.billingPortal.sessions.create({
      customer: req.session.customerid,
      return_url: 'http://localhost:3000/account',
    });
  
    res.redirect(session.url);
  });

haven’t found anything online about this, so not sure if it is doable, but just wondering! Thanks

Asynchronous functions not working on mobile browser

Whenever I try to use an async function it works on desktop but not on mobile. Using normal functions in my event listeners works fine on mobile and on desktop. Trying to call async functions in event listeners and outside of event listeners works on desktop but not on mobile. I’ve tried safari and chrome on my iphone xr and neither work. Any help would be much appreciated.

<!DOCTYPE html>
<html>

<body>

<h1>Current Temperature</h1>
<h2 id="currentTmp">1</h2>
<h1>Set Temp</h1>
<h2 id="setTmp">1</h2>
<button type="button" id="upButton">UP</button>
<button type="button" id="downButton">DOWN</button>
<script>
 
    var piTemps;
    var temp;
    var fullString;
    async function initial(){
        const response = await fetch('https://5206thermostatbucket.s3.us-east-2.amazonaws.com/helloworld.txt');
        var text = await response.text();
        var piTemps = text.split(" ");
        document.getElementById("setTmp").innerHTML = "you're seriously fucked bud"
        temp = parseInt(piTemps[0]);

        document.getElementById("setTmp").innerHTML = piTemps[0];
        document.getElementById("currentTmp").innerHTML = piTemps[1];
    };
    initial();

    document.getElementById("upButton").addEventListener('click', async function(){
        
        const response = await fetch('https://5206thermostatbucket.s3.us-east-2.amazonaws.com/helloworld.txt');
        var text = await response.text();
        var piTemps = text.split(" ");

        temp = parseInt(piTemps[0]);
        temp += 1;

        document.getElementById("setTmp").innerHTML = temp;
        fullString = temp.toString() + " " + piTemps[1];

        fetch('https://5206thermostatbucket.s3.us-east-2.amazonaws.com/helloworld.txt', {
            method: 'PUT',
            headers: {
            'Content-Type': 'text/plain'
            },
            body: fullString 
        });
        
        //document.getElementById("setTmp").innerHTML = "holy shit you're fucked";
    });

    document.getElementById("downButton").addEventListener('click', async function(){

        const response = await fetch('https://5206thermostatbucket.s3.us-east-2.amazonaws.com/helloworld.txt');
        var text = await response.text();
        var piTemps = text.split(" ");
        temp = parseInt(piTemps[0]);
        temp -= 1;

        document.getElementById("setTmp").innerHTML = temp;
        fullString = temp.toString() + " " + piTemps[1];
        console.log(fullString);

        fetch('https://5206thermostatbucket.s3.us-east-2.amazonaws.com/helloworld.txt', {
            method: 'PUT',
            headers: {
            'Content-Type': 'text/plain'
            },
            body: fullString 
        });

    });
</script>
</body>
</html>

JavaScript Variable to JSON

the code have this variable:

var t=new InfoBox;
        function o(map_property_link, map_property_image, map_property_neighborhood, map_property_address_street, map_property_price, i, s) {
            return'<a href="'+map_property_link+'" class="listing-img-container"><div class="infoBox-close"><i class="fa fa-times"></i></div><img src="'+map_property_image+'" alt=""><div class="rate-info"> <h5>$'+map_property_price+'</h5> <span>For Rent</span> </div><div class="listing-item-content"><h3>'+map_property_neighborhood+"</h3><span><i class='la la-map-marker'></i>"+map_property_address_street+"</span></div></a>"

var l=[[o("24_Property_Single.html", "assets/images/listing/1.jpg", "Grameen Sweets", "964 School Street, New York", "888.999,00"),
        23.72447089779572,
        90.42868673801422,
        1,
        '<i class="la la-home"></i>'],
        [o("24_Property_Single.html", "assets/images/listing/2.jpg", "Traditional Apartments", "212 5th Ave, New York", "777.999,00"),
        23.86009382,
        90.054245,
        2,
        '<i class="la la-home"></i>'],

How convert it to receive a json and not this variable?
I need receive this data of a JSON and supply the function
Thank You!

send a websocket message in a route, Express.js

The Goal:

Let’s say we have a marketplace full of shops. I’m creating a specific page localhost:3000/livePurchases/:storeId for a shop owner to monitor live notifications of when they got a new purchase.

enter image description here

enter image description here

alert('you received a new purchase') should be triggered by a WebSocket when an item is purchased.

The Problem:

I need to set up WebSockets on my express server so that the websocket can be triggered somewhere in my code different from where the websocket server was set up. But I don’t understand how to do this.

The websocket should send a message in the route "/newPurchase/:storeId":

app.js

const express = require("express");

module.exports = (config) => {
  const app = express();

  app.post("/newPurchase/:storeId", (req, res, next) => {
    const { storeid } = req.params;
    // trigger websocket message when client requests this route
  });

  return app;
};

But app.js is exported and run from another script, www.js. In real scenarios this is to connect a database before running the app.:

www.js

const app = require("../server/app")();

const port = process.env.PORT || "4000";
app.set("port", port);

app
  .listen(port)
  .on("listening", () =>
    console.log("info", `HTTP server listening on port ${port}`)
  );

module.exports = app;

So that means that the web socket server needs to be set up in www.js.

Below is a notifier service I got it from this tutorial, which seemed like it was trying to solve the problem I have, but it didn’t explain how to implement it. It is a class that handles the websocket.

NotifierService.js

const url = require("url");
const { Server } = require("ws");

class NotifierService {
  constructor() {
    this.connections = new Map();
  }

  connect(server) {
    this.server = new Server({ noServer: true });
    this.interval = setInterval(this.checkAll.bind(this), 10000);
    this.server.on("close", this.close.bind(this));
    this.server.on("connection", this.add.bind(this));
    server.on("upgrade", (request, socket, head) => {
      console.log("ws upgrade");
      const id = url.parse(request.url, true).query.storeId;

      if (id) {
        this.server.handleUpgrade(request, socket, head, (ws) =>
          this.server.emit("connection", id, ws)
        );
      } else {
        socket.destroy();
      }
    });
  }

  add(id, socket) {
    console.log("ws add");
    socket.isAlive = true;
    socket.on("pong", () => (socket.isAlive = true));
    socket.on("close", this.remove.bind(this, id));
    this.connections.set(id, socket);
  }

  send(id, message) {
    console.log("ws sending message");

    const connection = this.connections.get(id);

    connection.send(JSON.stringify(message));
  }

  broadcast(message) {
    console.log("ws broadcast");
    this.connections.forEach((connection) =>
      connection.send(JSON.stringify(message))
    );
  }

  isAlive(id) {
    return !!this.connections.get(id);
  }

  checkAll() {
    this.connections.forEach((connection) => {
      if (!connection.isAlive) {
        return connection.terminate();
      }

      connection.isAlive = false;
      connection.ping("");
    });
  }

  remove(id) {
    this.connections.delete(id);
  }

  close() {
    clearInterval(this.interval);
  }
}

module.exports = NotifierService;

Where I left off implementing the `NotifierService`

I added the websocket server with the NotifierService in www.js

www.js with websockets added

const app = require("../server/app")();
const NotifierService = require("../server/NotifierService.js");
const notifier = new NotifierService();
const http = require("http");
const server = http.createServer(app);
notifier.connect(server);
const port = process.env.PORT || "4000";
app.set("port", port);

server
  .listen(port)
  .on("listening", () =>
    console.log("info", `HTTP server listening on port ${port}`)
  );

module.exports = app;

But now how do I send the websocket message from the /livepPurchases route in app.js? If I create a new instance of NotifierService in app.js order to use the send method in the /livepPurchases route it won’t have access to the connections because it would be a different instance.

Front End:

App.js

import React from "react";

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import LiveStorePurchases from "./LiveStorePurchases";

function App(props) {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route exact path="/livePurchases/:storeId">
            <LiveStorePurchases />
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

export default App;

LivePurchaseServer.js

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

export default function LiveStorePurchases() {
  let { storeId } = useParams();
  const URL = "ws://127.0.0.1:4000?storeId=" + storeId;

  const [ws, setWs] = useState(new WebSocket(URL));

  useEffect(() => {
    ws.onopen = (e) => {
      newFunction(e);

      function newFunction(e) {
        alert("WebSocket Connected");
      }
    };

    ws.onmessage = (e) => {
      const message = e.data;
      alert(message);
    };

    return () => {
      ws.onclose = () => {
        alert("WebSocket Disconnected");
        setWs(new WebSocket(URL));
      };
    };
  }, [ws.onmessage, ws.onopen, ws.onclose, ws, URL]);

  return (
    <div
      style={{
        color: "red",
        fontSize: "4rem",
      }}
    >
      store: {storeId}
    </div>
  );
}

Javascript set variable value to html color picker hex value

I currently have a project with an html color picker. I also have a variable called color declared using JavaScript. What I’m wondering is how can I set the variable color constantly to the hex value of the color picker. For example, if I change the color picker to blue, the variable color will be set to #009DFF (Hex value for the blue color)

How can this be done? Fiddle containing code: https://jsfiddle.net/AidanYoung/pjw1mzL3/2/

Creating value checker

i want to make a value checker, which would send me my defined response after submitting value.
My requirements:

`If x = 1, x= 2, x=3, then i get response “Not passed”

If x = 4, x=5, x= 6, x= 7, x=8, x=9, x=10 response “passed!”

If x = 4-, x=5+, x=yes response “not a number”

If x= 0, x= 11, x= -2 response “wrong data”

If x is empty (No data entered) response “there are no data!”
`

I am getting stuck when i have to define 4-, 5+,yes as my function is reading those numbers without + and – signs after them and is giving answer “Passed” like for 4 and 5 without + and -, please check it, maybe you get some ideas how to fix it.

For full code: https://codesandbox.io/s/cocky-black-7mezc?file=/ifelse.html:0-2245
My code:

<h2>Ievadi datus</h2>
    <span contenteditable="true" ><p id="ievad"></p></span>
    <button id="poga1">Check!</button>
    <h2>Rezultāts</h2><br>
    <span contenteditable="true" ><p id="izv">Vispirms ievadi datus!</p></span>

And Javascript:

var rezultats = "";
    
    document.getElementById("poga1").onclick = function () 
    {
    
    let izv = document.getElementById("izv");
    let vertejums = document.getElementById("ievad");
    let rezultats = parseFloat(vertejums.textContent);
    return nep(rezultats);
    };
      

    function nep(rezultats){


        if (rezultats <= 0 || rezultats > 10.0){
            izvads = "Wrong data" ;
        }

        else if (rezultats < 4.0){
            izvads = "Not passed!";
        }

        else if (rezultats <= 10.0){
            izvads = "Passed!" ;
        }

        else if (rezultats == "4-", "5+", "yes"){
            izvads = "It's not a number!" ;
        }

        else{
            izvads = "There are no data!" ;
        }

    izv = document.getElementById("izv");
    izv.innerHTML = izvads;
    }

Will be thankful for help!

How do I select other objects in an array that has the same object in javascript and json?

I’m trying to create a code structure where people will list products based on the options they choose, but I got stuck at one point.

I’m pulling the data from the json file but I’m trying to provide the condition as follows. I want to extract the titles, prices and other information from the arrays with the same etiket values and print them to the document.

my Json data:

[
{
    "id": 1,
    "title": "Zincir Tasarımlı El Çantası",
    "price": "49.90",
    "upPrice": "69.90",
    "currency": "&#8378;",
    "images": "./images/yeni.jpg",
    "etiket": {
        "cinsiyet": "kadin",
        "yas": "yas16-20",
        "konsept": "yilbasi"
    }
},
{
    "id": 2,
    "title": "Tüylü Kısa Kol Çanta",
    "price": "74.50",
    "upPrice": "99.90",
    "currency": "&#8378;",
    "images": "./images/yeni1.jpg",
    "etiket": {
        "cinsiyet": "kadin",
        "yas": "yas20-30",
        "konsept": "yilbasi"
    }
},
{
    "id": 3,
    "title": "Zincir Detaylı Kemer Tokalı Çanta",
    "price": "89.90",
    "upPrice": "99.90",
    "currency": "&#8378;",
    "images": "./images/yeni3.jpg",
    "etiket": {
        "cinsiyet": "erkek",
        "yas": "yas16-20",
        "konsept": "yilbasi"
    }
},
{
    "id": 4,
    "title": "Zincirli Uzun Kol Deri Çanta",
    "price": "69.90",
    "upPrice": "89.90",
    "currency": "&#8378;",
    "images": "./images/yeni4.jpg",
    "etiket": {
        "cinsiyet": "erkek",
        "yas": "yas20-30",
        "konsept": "yilbasi"
    }
},
{
    "id": 5,
    "title": "Zincir Tasarımlı El Çantası",
    "price": "49.90",
    "upPrice": "69.90",
    "currency": "&#8378;",
    "images": "./images/yeni5.jpg",
    "etiket": {
        "cinsiyet": "erkek",
        "yas": "yas30-40",
        "konsept": "yilbasi"
    }
},
{
    "id": 6,
    "title": "Zincirli Deri Desenli Çanta",
    "price": "109.90",
    "upPrice": "129.90",
    "currency": "&#8378;",
    "images": "./images/yeni6.jpg",
    "etiket": {
        "cinsiyet": "erkek",
        "yas": "yas45ustu",
        "konsept": "yilbasi"
    }
},
{
    "id": 7,
    "title": "Kısa Kollu Deri Çanta",
    "price": "199.90",
    "upPrice": "269.90",
    "currency": "&#8378;",
    "images": "./images/yeni7.jpg",
    "etiket": {
        "cinsiyet": "kadin",
        "yas": "yas30-45",
        "konsept": "yilbasi"
    }
},
{
    "id": 8,
    "title": "Kahverengi Deri Desenli Kısa Kol Çanta",
    "price": "349.90",
    "upPrice": "369.90",
    "currency": "&#8378;",
    "images": "./images/yeni8.jpg",
    "etiket": {
        "cinsiyet": "kadin",
        "yas": "yas45ustu",
        "konsept": "yilbasi"
    }
}]

I’m giving an example. I want to draw the titles of the same “yilbasi” values, “yas16-20” values and “kadin” values to the page with innerHTML.

But I don’t know how to pull the data of the ones with the same values. I have not been able to create its structure. I want to do it with pure javascript if possible.

How to create accordions so only 1 stays open at a time?

I am having some difficulty using using an accordion in HTML & JS. I am trying to code it so only one accordion is open at a time. If someone clicks and opens a new accordion, all the other should close. This my HTML.

 <div class="accordion">
        <div class="accordion-item">
          <div class="accordion-item-header">
            HUMBER RADIO
          </div>
          <div class="accordion-item-body">
            <div class="accordion-item-body-content">
                <ul>
                    <li><a href="">RADIO NEWS</a></li>
                    <li><a href="">PODCAST</a></li>                 
                    <li><a href="">CONTENT</a></li>                
                </ul>
            </div>
          </div>
        </div>
        </div>
    
        <div class="accordion">
            <div class="accordion-item">
              <div class="accordion-item-header">
                TV NEWS
              </div>
              <div class="accordion-item-body">
                <div class="accordion-item-body-content">
                    <ul>
                        <li><a href="">COVID UPDATES</a></li>
                        <li><a href="">NORTH CAMPUS NEWS</a></li>                 
                        <li><a href="">LAKESHORE CAMPUS NEWS</a></li>                
                    </ul>
                </div>
              </div>
            </div>
            </div>

Here is the JavaScript for the code. It can open all of them, but I am struggling to program it so the others close.

window.onload = pageReady;

function pageReady() {

    const accordionItemHeaders = document.querySelectorAll(".accordion-item-header");

    accordionItemHeaders.forEach(accordionItemHeader => {
      accordionItemHeader.addEventListener("click", event => {
    
        accordionItemHeader.classList.toggle("active");
        const accordionItemBody = accordionItemHeader.nextElementSibling;
        if(accordionItemHeader.classList.contains("active")) {
          accordionItemBody.style.maxHeight = "100px";
        }
        else {
          accordionItemBody.style.maxHeight = "0px";
        }
        
      });
    });
}

I have two JQuery Ajax API calls to a REST API, one doesn’t work why?

I’m doing a get REST api request to a server. The server houses automation jobs what I’m looking to kick off with parameters.

var jobURL = "https://hostname/api/v1/tasks"; 

$.ajax({
    url: jobURL,
    method: 'GET',
    async: false,
    contentType: "application/json",
    data: {
        name: '*JOBNAME*'
    },
    headers: {
        'Authorization': 'Bearer '+ obj.access_token,
        'Content-type': 'application/x-www-form-urlencoded',
        Accept:'application/json'
    },
    success: function(data){
        taskname_obj = data    // result
}

I’m doing this per the documentation of the server product and it is working.

https://docs.ipswitch.com/MOVEit/Automation2021/API/REST-API/index.html#_gettaskusingget

I have a successful request, with items returned in the ‘taskname_obj’ variable.
With that said I’m trying to use the same sort of code for another call.

// THIS IS WORKING TO JOB WITHOUT PARAMS.

        // Let's run the job. 
        $.ajax({
            url: jobURL,
            method: 'POST',
            async: false,
            headers: {
                'Authorization': 'Bearer '+ obj.access_token
            },
            success: function(data){
                taskname_obj2 = data    // result
            }
        })

SO I’m doing the above code to work with the endpoint in the link below:

https://docs.ipswitch.com/MOVEit/Automation2021/API/REST-API/index.html#_starttaskusingpost

Again I am success, I can start my job. I have indication of success returned into taskname_obj2.

With all that said, I am trying to start this with parameters. I suppose I have to put that into the “data:” item, and I shout use JSON. So… I do the following…

var payload = { 
    USER_ID: "",
    BEGDATE: "060121",
    ENDDATE: "121521"
};

$.ajax({
    url: jobURL,
    method: 'POST',
    async: false,
    contentType: 'application/json',
    data: payload,
    headers: {
        'Authorization': 'Bearer '+ obj.access_token,
        'Content-type': 'application/x-www-form-urlencoded',
        Accept:'application/json'
    },
    success: function(data){
        taskname_obj2 = data    // result
    }
})

This doesn’t work. I am getting a 415 error back from the server for unsupported media type. I also tried not using JSON.stringify for the data item but I also get a 415 with that.

I think I’m not telling it correctly how to read my JSON. Can anybody help me understand what I’m doing wrong?

I also tried adding this contentType: 'application/json', to no avail.

how to removechild element from list in JavaScript

when I add a element from right to left I can see element in both view by name and view by code

when I perform delete how to remove value from both the list and disable false for both lists

<form name="adminForm" id="formAdmin" method="post" action="http://localhost:7003/ccrSrc/initAdmin.do">
<table style="margin-top: -15px" cellspacing="0" cellpadding="0" border="0" width="760">
   <tbody>
      <tr bgcolor="#EEEEEE">
         <td width="800" valign="top" style="margin:0px; padding: 0px;">
            <table class="orgtable">
               <tbody>
                  <tr>
                     <td class="tabletitle2" width="40%" nowrap="">Available Orgs:</td>
                     <td class="tabletitle2" width="20%">&nbsp;</td>
                     <td class="tabletitle2" width="40%" nowrap="">Assigned Orgs:</td>
                  </tr>
                  <tr>
                     <!--Available Organizations-->
                     <td width="40%" class="bodytext6">
                        <div class="container">
                           <label class="section-label">Status:</label>
                           <input class="radioBtn" type="radio" name="status" value="ACTIVE" checked="" onclick="javascript:changeStatus(1);">
                           <label class="section-label">Active</label>
                           <input class="radioBtn" type="radio" name="status" value="INACTIVE" onclick="javascript:changeStatus(2);">
                           <label class="section-label">Inactive</label>
                           <br/>
                           <label class="section-label">View:</label>
                           <input class="radioBtn" type="radio" name="viewGrp" value="BYNAME" checked="" onclick="javascript:changeView('BYNAME');">
                           <label class="section-label">    Org Name</label>
                           <input class="radioBtn" type="radio" name="viewGrp" value="BYCODE" onclick="javascript:changeView('BYCODE');">
                           <label class="section-label">Org Code</label>
                        </div>
                        <div id="Status1" style="cursor:default; display: inline;">
                           <select id="" name="activeChnl" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%">
                              <option value="1">Accountancy, Banking and Finance</option>
                              <option value="2">Animal and Plant Resource</option>
                              <option value="3">Business, Consulting and Management</option>
                              <option value="4">Charity and Voluntary Work</option>
                              <option value="5">Creative Arts and Design</option>
                              <option value="6">Energy and Utilities</option>
                              <option value="7">Engineering and Manufacturing</option>
                              <option value="8">Enviromemt amd Agriculture</option>
                              <option value="9">Healthcare</option>
                              <option value="10">Hospitality and Events Management</option>
                           </select>
                        </div>
                        <div id="Status2" style="cursor:default; display: none;">
                           <select name="inactiveChnl" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%">
                              <option value="11">Information, Research and Analysis</option>
                              <option value="12">Insurance and Pensions</option>
                              <option value="13">Law</option>
                              <option value="14">Law Enforcement and Security</option>
                              <option value="15">Leisure, Sport and Tourism</option>
                              <option value="16">Marketing, Advertising and PR</option>
                              <option value="17">Media and Internet</option>
                              <option value="18">Performing Arts</option>
                              <option value="19">Property and Construction</option>
                              <option value="20">Public Services and Administration</option>
                           </select>
                        </div>
                        <div id="Status3" style="cursor:default; display: none;">
                           <select name="activeChnlByCode" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%">
                              <option value="1">001 Accountancy, Banking and Finance</option>
                              <option value="2">002 Animal and Plant Resource</option>
                              <option value="3">003 Business, Consulting and Management</option>
                              <option value="4">004 Charity and Voluntary Work</option>
                              <option value="5">005 Creative Arts and Design</option>
                              <option value="6">006 Energy and Utilities</option>
                              <option value="7">007 Engineering and Manufacturing</option>
                              <option value="8">008 Enviromemt amd Agriculture</option>
                              <option value="9">009 Healthcare</option>
                              <option value="10">010 Hospitality and Events Management</option>
                           </select>
                        </div>
                        <div id="Status4" style="cursor:default; display: none;">
                           <select name="inactiveChnlByCode" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%">
                              <option value="11">011 Information, Research and Analysis</option>
                              <option value="12">012 Insurance and Pensions</option>
                              <option value="13">013 Law</option>
                              <option value="14">014 Law Enforcement and Security</option>
                              <option value="15">015 Leisure, Sport and Tourism</option>
                              <option value="16">016 Marketing, Advertising and PR</option>
                              <option value="17">017 Media and Internet</option>
                              <option value="18">018 Performing Arts</option>
                              <option value="19">019 Property and Construction</option>
                              <option value="20">020 Public Services and Administration</option>
                           </select>
                        </div>
                     </td>
                     <td width="4%" align="center" nowrap="">
                        <button class="addRemoveBtn" name="btnAdd" type="button">&gt;&gt;</button>
                        <br><br><br>
                        <button class="addRemoveBtn" name="btnRemove" type="button">&lt;&lt;</button>
                     </td>
                     <td width="48%" class="smalltext0">
                        <div id="activeStatus1" style="cursor: default; display: inline;">
                           <select name="assignedActiveChnl" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%;height:347px;">
                           </select>
                        </div>
                        <div id="activeStatus2" style="cursor: default; display: none;">
                           <select name="assignedInactiveChnl" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%;height:347px;">
                           </select>
                        </div>
                        <div id="activeStatus3" style="cursor:default; display: none;">
                           <select name="assignedActiveChnlByCode" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%;height:347px;">
                           </select>
                        </div>
                        <div id="activeStatus4" style="cursor:default; display: none;">
                           <select name="assignedInactiveChnlByCode" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%;height:347px;">
                           </select>
                        </div>
                     </td>
                  </tr>
                  <tr>
                     <td></td>
                     <td>
                     </td>
                     <td align="right">
                        <button id="cancel" style="width:75px;" type="button" onclick="javascript:loadUserOrgAction();">Cancel</button>
                        <button id="save" style="width:75px;" type="button" onclick="javascript:loadUserOrgAction();">Save</button>
                     </td>
                  </tr>
               </tbody>
            </table>
         </td>
      </tr>
   </tbody>
</table>
</form> 

below is the JavaScript function for add and remove
when add click is performed i can add value to both assigned list as code and name same behaviour should be work for when i click on remove how can i achieve these ?

var tempAddedActiveOrgs = [];
var tempAddedInactiveOrgs = [];
var tempAddedActiveOrgsByCode = [];
var tempAddedInactiveOrgsByCode = [];

let View1 = true;
let View2 = false;
let Status1 = true;
let Status2 = false;
let ActiveStatus1 = true;
let ActiveStatus2 = false;

function changeStatus(statusId) {
    var frm = document.getElementById('formAdmin');
    var activChnls = frm.activeChnl;
    var inactivChnls = frm.inactiveChnl;
    var sectionName = "Status" + statusId;
    //reset sections
    view1 = false;
    document.getElementById("Status1").style.display = 'none';
    view2 = false;
    document.getElementById("Status2").style.display = 'none';
    //display appropriate section
    if (sectionName == "Status1") {
        Status1 = true;
        document.getElementById("Status1").style.display = 'inline';
        if (activChnls.length < 1) {
            alert('You currently have no Partners assigned. To update your list of assigned Partners, please visit go/updatemyccr and submit a request form.');
            disableButtons();
        } else if (document.getElementById('formAdmin').viewGrp.value == 'BYNAME') {
            document.getElementById("Status1").style.display = 'inline';
            document.getElementById("Status2").style.display = 'none';
            document.getElementById("Status3").style.display = 'none';
            document.getElementById("Status4").style.display = 'none';
            document.getElementById("activeStatus1").style.display = 'inline';
            document.getElementById("activeStatus2").style.display = 'none';
            document.getElementById("activeStatus3").style.display = 'none';
            document.getElementById("activeStatus4").style.display = 'none';
        } else if (document.getElementById('formAdmin').viewGrp.value == 'BYCODE') {
            document.getElementById("Status1").style.display = 'none';
            document.getElementById("Status2").style.display = 'none';
            document.getElementById("Status3").style.display = 'inline';
            document.getElementById("Status4").style.display = 'none';
            document.getElementById("activeStatus1").style.display = 'none';
            document.getElementById("activeStatus2").style.display = 'none';
            document.getElementById("activeStatus3").style.display = 'inline';
            document.getElementById("activeStatus4").style.display = 'none';
        } else {
            enableButtons();
            activChnls.selectedIndex = "0";
            activChnls.focus();
            clearSearch();
        }
    } else if (sectionName == "Status2") {
        Status2 = true;
        document.getElementById("Status2").style.display = 'inline';
        if (inactivChnls.length < 1) {
            disableButtons();
        } else if (document.getElementById('formAdmin').viewGrp.value == 'BYNAME') {
            document.getElementById("Status1").style.display = 'none';
            document.getElementById("Status2").style.display = 'inline';
            document.getElementById("Status3").style.display = 'none';
            document.getElementById("Status4").style.display = 'none';
            document.getElementById("activeStatus1").style.display = 'none';
            document.getElementById("activeStatus2").style.display = 'inline';
            document.getElementById("activeStatus3").style.display = 'none';
            document.getElementById("activeStatus4").style.display = 'none';
        } else if (document.getElementById('formAdmin').viewGrp.value == 'BYCODE') {
            document.getElementById("Status1").style.display = 'none';
            document.getElementById("Status2").style.display = 'none';
            document.getElementById("Status3").style.display = 'none';
            document.getElementById("Status4").style.display = 'inline';
            document.getElementById("activeStatus1").style.display = 'none';
            document.getElementById("activeStatus2").style.display = 'none';
            document.getElementById("activeStatus3").style.display = 'none';
            document.getElementById("activeStatus4").style.display = 'inline';
        } else {
            enableButtons();
            inactivChnls.selectedIndex = "0";
            inactivChnls.focus();
            clearSearch();
        }
    } else {

        Status1 = true;
        document.getElementById("Status1").style.display = 'inline';
        statusId = "1";
    }
}

function changeView(type) {
    if (type == "BYNAME" && document.getElementById('formAdmin').status.value == 'ACTIVE') {
        document.getElementById("Status1").style.display = 'inline';
        document.getElementById("Status2").style.display = 'none';
        document.getElementById("Status3").style.display = 'none';
        document.getElementById("Status4").style.display = 'none';
        document.getElementById("activeStatus1").style.display = 'inline';
        document.getElementById("activeStatus2").style.display = 'none';
        document.getElementById("activeStatus3").style.display = 'none';
        document.getElementById("activeStatus4").style.display = 'none';
    } else if (type == "BYNAME" && document.getElementById('formAdmin').status.value == 'INACTIVE') {
        document.getElementById("Status1").style.display = 'none';
        document.getElementById("Status2").style.display = 'inline';
        document.getElementById("Status3").style.display = 'none';
        document.getElementById("Status4").style.display = 'none';
        document.getElementById("activeStatus1").style.display = 'none';
        document.getElementById("activeStatus2").style.display = 'inline';
        document.getElementById("activeStatus3").style.display = 'none';
        document.getElementById("activeStatus4").style.display = 'none';

    } else if (type == "BYCODE" && document.getElementById('formAdmin').status.value == 'ACTIVE') {
        document.getElementById("Status1").style.display = 'none';
        document.getElementById("Status2").style.display = 'none';
        document.getElementById("Status3").style.display = 'inline';
        document.getElementById("Status4").style.display = 'none';
        document.getElementById("activeStatus1").style.display = 'none';
        document.getElementById("activeStatus2").style.display = 'none';
        document.getElementById("activeStatus3").style.display = 'inline';
        document.getElementById("activeStatus4").style.display = 'none';

    } else if (type == "BYCODE" && document.getElementById('formAdmin').status.value == 'INACTIVE') {
        document.getElementById("Status1").style.display = 'none';
        document.getElementById("Status2").style.display = 'none';
        document.getElementById("Status3").style.display = 'none';
        document.getElementById("Status4").style.display = 'inline';
        document.getElementById("activeStatus1").style.display = 'none';
        document.getElementById("activeStatus2").style.display = 'none';
        document.getElementById("activeStatus3").style.display = 'none';
        document.getElementById("activeStatus4").style.display = 'inline';

    }
}

adminForm.btnAdd.onclick = () => {
    if (document.getElementById("Status1").style.display == 'inline') {
        addActiveChnlOrgs();
    } else if (document.getElementById("Status2").style.display == 'inline') {
        addInactiveChnlOrgs();
    }
}

function addActiveChnlOrgs() {
    var frm = document.getElementById('formAdmin');
    var assignedActiveChnls = frm.assignedActiveChnl;
    var activeChnls = frm.activeChnl;
    var activeChnlByCode = frm.activeChnlByCode;
    var assignedActiveChnlByCode = frm.assignedActiveChnlByCode;
    //adding active selected chnl org by name to assigned chnl org by name 
    for (i = 0; i < activeChnls.length; i++) {
        if (activeChnls[i].selected == true) {
            var opt = document.createElement('option');
            opt.value = activeChnls[i].value;
            opt.innerHTML = activeChnls[i].label;
            assignedActiveChnls.appendChild(opt);
            if (tempAddedActiveOrgs.indexOf(opt.value) === -1) {
                tempAddedActiveOrgs.push(opt.value);
            }
            activeChnls[i].disabled = true;
        }
    }

    //adding active selected chnl org by name to assigned chnl org by code 
    for (i = 0; i < activeChnls.length; i++) {
        if (activeChnls[i].selected == true) {
            for (j = 0; j < activeChnlByCode.length; j++) {
                if (activeChnls[i].value == activeChnlByCode[j].value) {
                    var opt = document.createElement('option');
                    opt.value = activeChnlByCode[j].value;
                    opt.innerHTML = activeChnlByCode[j].label;
                    assignedActiveChnlByCode.appendChild(opt);
                    if (tempAddedActiveOrgsByCode.indexOf(opt.value) === -1) {
                        tempAddedActiveOrgsByCode.push(opt.value);
                    }
                    activeChnlByCode[j].disabled = true;
                }
            }
        }
    }
    activeChnls.selectedIndex = -1;
    activeChnlByCode.selectedIndex = -1;

    sortSelect(assignedActiveChnls);
    sortSelect(assignedActiveChnlByCode);
    extractLabelForDisplay(assignedActiveChnls);
    //color added orgs to blue
    for (var i = 0; i < assignedActiveChnls.length; i++) {
        for (var j = 0; j < tempAddedActiveOrgs.length; j++) {
            if (assignedActiveChnls[i].value == tempAddedActiveOrgs[j]) {
                assignedActiveChnls[i].style.color = "blue";
            }
        }
    }

    for (var i = 0; i < assignedActiveChnlByCode.length; i++) {
        for (var j = 0; j < tempAddedActiveOrgsByCode.length; j++) {
            if (assignedActiveChnlByCode[i].value == tempAddedActiveOrgsByCode[j]) {
                assignedActiveChnlByCode[i].style.color = "blue";
            }
        }
    }
}

function addActiveChnlOrgsByCode() {
    var frm = document.getElementById('formAdmin');
    var assignedActiveChnlByCode = frm.assignedActiveChnlByCode;
    var activeChnlByCode = frm.activeChnlByCode;
    var assignedActiveChnls = frm.assignedActiveChnl;
    var activeChnls = frm.activeChnl;
    //adding active selected chnl org by code to assigned chnl org by code 
    for (i = 0; i < activeChnlByCode.length; i++) {
        if (activeChnlByCode[i].selected == true) {
            var opt = document.createElement('option');
            opt.value = activeChnlByCode[i].value;
            opt.innerHTML = activeChnlByCode[i].label;
            assignedActiveChnlByCode.appendChild(opt);
            if (tempAddedActiveOrgsByCode.indexOf(opt.value) === -1) {
                tempAddedActiveOrgsByCode.push(opt.value);
            }
            activeChnlByCode[i].disabled = true;
        }
    }
    //adding active selected chnl org by code to assigned chnl org by name
    for (i = 0; i < activeChnlByCode.length; i++) {
        if (activeChnlByCode[i].selected == true) {
            for (j = 0; j < activeChnls.length; j++) {
                if (activeChnlByCode[i].value == activeChnls[j].value) {
                    var opt = document.createElement('option');
                    opt.value = activeChnls[j].value;
                    opt.innerHTML = activeChnls[j].label;
                    assignedActiveChnls.appendChild(opt);
                    if (tempAddedActiveOrgs.indexOf(opt.value) === -1) {
                        tempAddedActiveOrgs.push(opt.value);
                    }
                    activeChnls[j].disabled = true;
                }
            }
        }
    }
    activeChnlByCode.selectedIndex = -1;
    activeChnls.selectedIndex = -1;

    sortSelect(assignedActiveChnls);
    sortSelect(assignedActiveChnlByCode);
    extractLabelForDisplay(assignedActiveChnls);
    //color added orgs to blue
    for (var i = 0; i < assignedActiveChnlByCode.length; i++) {
        for (var j = 0; j < tempAddedActiveOrgsByCode.length; j++) {
            if (assignedActiveChnlByCode[i].value == tempAddedActiveOrgsByCode[j]) {
                assignedActiveChnlByCode[i].style.color = "blue";
            }
        }
    }

    for (var i = 0; i < assignedActiveChnls.length; i++) {
        for (var j = 0; j < tempAddedActiveOrgs.length; j++) {
            if (assignedActiveChnls[i].value == tempAddedActiveOrgs[j]) {
                assignedActiveChnls[i].style.color = "blue";
            }
        }
    }
}

adminForm.btnRemove.onclick = () => {
    let frm = document.getElementById('formAdmin')
    let activeAssignedChnl = frm.assignedActiveChnl;
    let inActiveAssignedChnl = frm.assignedInactiveChnl;
    let activeAssignedChnlByCode = frm.assignedActiveChnlByCode;
    let assignedInactiveChnlByCode = frm.assignedInactiveChnlByCode;

    if (document.getElementById("Status1").style.display == 'inline') {
        if (activeAssignedChnlByCode.children.length > 0) {
            let activeChnlByCode = frm.activeChnlByCode;
            for (j = 0; j < activeAssignedChnlByCode.length; j++) {
                if (activeChnlByCode[j].value == activeAssignedChnl.value) {
                    activeChnlByCode[j].disabled = false
                }
            }
        }
        if (activeAssignedChnl.children.length > 0) {
            let activChnls = frm.activeChnl;
            for (i = 0; i < activChnls.length; i++) {
                if (activChnls[i].value == activeAssignedChnl.value) {
                    activChnls[i].disabled = false
                    activeAssignedChnl.removeChild(
                        activeAssignedChnl.options[activeAssignedChnl.selectedIndex]
                    )
                }
            }
        }
    } else if (document.getElementById("Status2").style.display == 'inline') {
        if (inActiveAssignedChnl.children.length > 0) {
            let inactivChnls = frm.inactiveChnl;
            for (i = 0; i < inactivChnls.length; i++) {
                if (inactivChnls[i].value == inActiveAssignedChnl.value) {
                    inactivChnls[i].disabled = false
                    inActiveAssignedChnl.removeChild(
                        inActiveAssignedChnl.options[inActiveAssignedChnl.selectedIndex]
                    )
                }
            }
        }
    } else if (document.getElementById("Status3").style.display == 'inline') {
        if (activeAssignedChnlByCode.children.length > 0) {
            let activeChnlByCode = frm.activeChnlByCode;
            for (i = 0; i < activeChnlByCode.length; i++) {
                if (activeChnlByCode[i].value == activeAssignedChnlByCode.value) {
                    activeChnlByCode[i].disabled = false
                    activeAssignedChnlByCode.removeChild(
                        activeAssignedChnlByCode.options[activeAssignedChnlByCode.selectedIndex]
                    )
                }
            }
        }
    } else if (document.getElementById("Status4").style.display == 'inline') {
        if (assignedInactiveChnlByCode.children.length > 0) {
            let inactiveChnlByCode = frm.inactiveChnlByCode;
            for (i = 0; i < inactiveChnlByCode.length; i++) {
                if (inactiveChnlByCode[i].value == assignedInactiveChnlByCode.value) {
                    inactiveChnlByCode[i].disabled = false
                    assignedInactiveChnlByCode.removeChild(
                        assignedInactiveChnlByCode.options[assignedInactiveChnlByCode.selectedIndex]
                    )
                }
            }
        }
    }
    adminForm.empNumber.value = document.getElementById("employeeNumberValue").textContent;
    clearSearchBoxes();
}

Adding branches to a star using JavaScript

I’m still a beginner at programmation and I am currently working on a script aiming at creating a 5-branch star and adding new branches whenever I click onto the button in the middle of the star. I advanced a lot already but I’m blocked at the Java stage, since I can’t manage to get the new branches spawning at the star’s centre.
Here is my code so far:

console.log("Test")

window.addEventListener('DOMContentLoaded', () => {
  const centre = document.getElementById("centre");

  let compteurBranches = 0;
  centre.querySelectorAll(":scope > div").forEach(el => {
    el.style.setProperty("--image-numero", compteurBranches);
    compteurBranches++;
  });

  centre.style.setProperty("--compteur-branches", compteurBranches);

  document.getElementById("bouton").addEventListener("click", (event) => {
    event.preventDefault();

    const imageNumero = compteurBranches;
    const html = `<div style="--image-numero:${imageNumero};"><img src="branch.png" class="image"></div>`;
    centre.insertAdjacentHTML("afterbegin", html);

    compteurBranches++;
    centre.style.setProperty("--compteur-branches", compteurBranches); 
  });
});
main{
    font-family: "Montserrat", sans-serif;
}

div#main {
    width: 900px;
    height: 900px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;

}

div#centre {
    position: absolute;
    height: 0px;
    width: 100%;
    top: 50%;
    left: 50%;
    display: inline-block;
}

button#bouton{
    width: 200px;
    height: 200px;
    filter: drop-shadow(0px 0px 8px black);
    border: 1px black solid;
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
    z-index: 1;
    left: 50%;
    top: 0px;
    position: absolute;
}

div#centre > div { 
    position: absolute;
    z-index: 0;
    background-repeat: no-repeat;
    --angle: calc(90deg + var(--image-numero) * 360deg / var(--compteur-branches));
    transform: rotate(var(--angle));
}


.image {
    transform: rotate(calc(-1 * var(--angle)));
    filter: hue-rotate(var(--angle));
    background-image: url(./branch.png);
    background-repeat: no-repeat;
    transform-origin: top;
    width: 200px;
    height: 344px;
    position: absolute;
    left: 50%;
    top: 100px;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="dm.css">
    <title>DM</title>
</head>
<body>
    <div id="main" style="--compteur-branches:5;"> 
        <div id="centre">
            <div class="image" id="image1" style="--image-numero:0;"></div>
            <div class="image" id="image2" style="--image-numero:1;"></div>
            <div class="image" id="image3" style="--image-numero:2;"></div>
            <div class="image" id="image4" style="--image-numero:3;"></div>
            <div class="image" id="image5" style="--image-numero:4;"></div>
            <button id="bouton">
                Cliquer pour ajouter une branche
            </button>
        </div>
    </div>
</body>
<script type="text/javascript" src="dm.js"></script>
</html>

Client (JRE) read server (node) variables directly?

I am trying to set up a server where clients can connect and essentially “raise their hand”, which lights up for every client, but only one at a time. I currently just use the express module to send a POST response on button-click. The server takes it as JSON and writes it to a file. All the clients are constantly requesting this file to check the status to see if the channel is clear.

I suspect there is a more streamlined approach for this, but I do not know what modules or methods might be best. Can the server push variables to the clients in some way, instead of the clients constantly requesting a file? Then the client script can receive the variable and change the page elements accordingly?