How can I find book chapters followed by roman numbers or digits?

I want to extract all chapter words with their following numbers using regex. This is an example text:

Chapter 1: The first chapter
           Theory
           Examples
Chapter 2: The second chapter
           Theory
           Examples
CHAPTER 3: The third chapter
Chapter 4: addition information for chapter 1

The regexp should return [“Chapter 1”, “Chapter 2”, “CHAPTER 3”, “CHAPTER 4”] in bold but not the chapter words somewhere else.
The word Chapter should have the first character in uppercase, and the rest can be lowercase or all uppercase, like “CHAPTER”.

Can somebody help me?
Thank you in advance.

Can’t fetch file and add to element contents

I have this code setup for loading a html file into the contents of an element:

const contentElement = "content";
import { ElementController } from "ElementController.js";
ElementController.Set(contentElement, "test.html");

In my ElementController i have these functions:

function Set(elementId, url, callback) {
    Clear(elementId);
    Append(elementId, url, callback);
}
/*
    # Append the content of a file to an element
    @param {string} element - The element to load the content into
    @param {string} url - The url to load the content from
    @optional param {function} callback - The function to call after the content has been loaded
*/
function Append(elementId, url, callback) {
    fetch(url)
        .then(response => response.text())
        .then(data => {
            document.getElementById(elementId).insertAdjacentHTML('afterbegin', data);
            if (callback) {
                callback();
            }
        })
        .catch(error => console.error('Error:', error));
}

I get no error in console, and the network tab does not appear to request the html file either. What am i doing wrong here?

Why is my Tic-Tac-Toe AI placing two O’s? [closed]

<html>
  <body>
    <style>
      td {
        border: 1px solid black;
        height: 50px;
        width: 50px;
      }
    </style>
    <script>
      let O1 = false;
      let X1 = false;
      let O2 = false;
      let X2 = false;
      let O3 = false;
      let X3 = false;
      let O4 = false;
      let X4 = false;
      let O5 = false;
      let X5 = false;
      let O6 = false;
      let X6 = false;
      let O7 = false;
      let X7 = false;
      let O8 = false;
      let X8 = false;
      let O9 = false;
      let X9 = false;
      let turn = 0;
      let XWinNum = 0
      let OWinNum = 0
      function Xon1() {
        if (O1 === false && X1 === false && turn === 0) {
          document.getElementById("1").innerHTML = 'X';
          X1 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon2() {
        if (O2 === false && X2 === false && turn === 0) {
          document.getElementById("2").innerHTML = 'X';
          X2 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon3() {
        if (O3 === false && X3 === false && turn === 0) {
          document.getElementById("3").innerHTML = 'X';
          X3 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon4() {
        if (O4 === false && X4 === false && turn === 0) {
          document.getElementById("4").innerHTML = 'X';
          X4 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon5() {
        if (O5 === false && X5 === false && turn === 0) {
          document.getElementById("5").innerHTML = 'X';
          X5 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon6() {
        if (O6 === false && X6 === false && turn === 0) {
          document.getElementById("6").innerHTML = 'X';
          X6 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon7() {
        if (O7 === false && X7 === false && turn === 0) {
          document.getElementById("7").innerHTML = 'X';
          X7 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon8() {
        if (O8 === false && X8 === false && turn === 0) {
          document.getElementById("8").innerHTML = 'X';
          X8 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function Xon9() {
        if (O9 === false && X9 === false && turn === 0) {
          document.getElementById("9").innerHTML = 'X';
          X9 = true;
          turn++
          setTimeout(compMove, 1000);
        }
      }
      function compMove() {
        checkForWin()
        if (turn === 1) {
          if(X1 === true && X2 === true && X3 === false && O3 === false && turn === 1) {
            document.getElementById("3").innerHTML = 'O';
          O3 = true
          turn--
          }
          if(X1 === true && X3 === true && X2 === false && O2 === false && turn === 1) {
            document.getElementById("2").innerHTML = 'O';
          O2 = true
          turn--
          }
          if(X2 === true && X3 === true && X1 === false && O1 === false && turn === 1) {
            document.getElementById("1").innerHTML = 'O';
          O1 = true
          turn--
          }
          if(X3 === true && X4 === true && X5 === false && O5 === false && turn === 1) {
            document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X3 === true && X5 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X4 === true && X5 === true && X6 === false && O6 === false && turn === 1) {
            document.getElementById("6").innerHTML = 'O';
          O6 = true
          turn--
          }
          if(X7 === true && X8 === true && X9 === false && O9 === false && turn === 1) {
            document.getElementById("9").innerHTML = 'O';
          O9 = true
          turn--
          }
          if(X7 === true && X9 === true && X8 === false && O8 === false && turn === 1) {
            document.getElementById("8").innerHTML = 'O';
          O8 = true
          turn--
          }
          if(X8 === true && X9 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X1 === true && X4 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X1 === true && X7 === true && X4 === false && O4 === false && turn === 1) {
            document.getElementById("4").innerHTML = 'O';
          O4 = true
          turn--
          }
          if(X7 === true && X4 === true && X1 === false && O1 === false && turn === 1) {
            document.getElementById("1").innerHTML = 'O';
          O1 = true
          turn--
          }
          if(X2 === true && X5 === true && X8 === false && O8 === false && turn === 1) {
            document.getElementById("8").innerHTML = 'O';
          O8 = true
          turn--
          }
          if(X2 === true && X8 === true && X5 === false && O5 === false && turn === 1) {
            document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X5 === true && X8 === true && X2 === false && O2 === false && turn === 1) {
            document.getElementById("2").innerHTML = 'O';
          O2 = true
          turn--
          }
          if(X3 === true && X6 === true && X9 === false && O9 === false && turn === 1) {
            document.getElementById("9").innerHTML = 'O';
          O9 = true
          turn--
          }
          if(X3 === true && X9 === true && X6 === false && O6 === false && turn === 1) {
            document.getElementById("6").innerHTML = 'O';
          O6 = true
          turn-- 
          }
          if(X9 === true && X6 === true && X3 === false && O3 === false && turn === 1) {
          document.getElementById("3").innerHTML = 'O';
          O3  = true
          turn--
          }
          if(X5 === true && X7 === true && X3 === false && O3 === false && turn === 1) {
            document.getElementById("3").innerHTML = 'O';
          O3 = true
          turn--
          }
          if(X5 === true && X3 === true && X7 === false && O7 === false && turn === 1) {
            document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X7 === true && X3 === true && X5 === false && O5 === false && turn === 1) {
            document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X1 === true || X2 === true || X3 === true || X4 === true || X5 === true || X6 === true || X7 === true || X8 === true || X9 === true && turn === 1) {
            if(O5 === false && X5 === false){
          document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--} else {
             if(X1 === false && O1 === false){
              document.getElementById("1").innerHTML = 'O';
          O1 = true
          turn--
          }
          if(X2 === false && O2 === false && turn === 1){
              document.getElementById("2").innerHTML = 'O';
          O2 = true
          turn--
          }
          if(X3 === false && O3 === false && turn === 1){
              document.getElementById("3").innerHTML = 'O';
          O3 = true
          turn--
          }
          if(X4 === false && O4 === false && turn === 1){
              document.getElementById("4").innerHTML = 'O';
          O4 = true
          turn--
          }
          if(X5 === false && O5 === false && turn === 1){
              document.getElementById("5").innerHTML = 'O';
          O5 = true
          turn--
          }
          if(X6 === false && O6 === false && turn === 1){
              document.getElementById("6").innerHTML = 'O';
          O6 = true
          turn--
          }
          if(X7 === false && O7 === false && turn === 1){
              document.getElementById("7").innerHTML = 'O';
          O7 = true
          turn--
          }
          if(X8 === false && O8 === false && turn === 1){
              document.getElementById("8").innerHTML = 'O';
          O8 = true
          turn--
          }
          if(X9 === false && O9 === false && turn === 1){
              document.getElementById("9").innerHTML = 'O';
          O9 = true
          turn--
          }
         
          }
          
          }
       
          }
          checkForWin()
          }
          function checkForWin() {
          if(X1 === true && X2 === true && X3 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X4 === true && X5 === true && X6 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X7 === true && X8 === true && X9 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X1 === true && X4 === true && X7 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X2 === true && X5 === true && X8 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X3 === true && X6 === true && X9 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X1 === true && X5 === true && X9 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(X3 === true && X5 === true && X7 === true){
          setTimeout(XWins, 100)
          turn+=2
          }
          if(O1 === true && O2 === true && O3 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O4 === true && O5 === true && O6 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O7 === true && O8 === true && O9 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O1 === true && O4 === true && O7 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O2 === true && O5 === true && O8 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O3 === true && O6 === true && O9 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O1 === true && O5 === true && O9 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          if(O3 === true && O5 === true && O7 === true){
          setTimeout(OWins, 100)
          turn+=2
          }
          }
          function OWins() {
            alert("O Wins")
            OWinNum++
            document.getElementById("win").innerHTML = 'X:' + XWinNum + '-' + 'O:' + OWinNum
          }
          function XWins() {
            alert("X Wins")
            XWinNum+=0.5
            document.getElementById("win").innerHTML = 'X:' + XWinNum + ' - ' + 'O:' + OWinNum
          }
          function Restart() {
            document.getElementById("1").innerHTML = '-'
            document.getElementById("2").innerHTML = '-'
            document.getElementById("3").innerHTML = '-'
            document.getElementById("4").innerHTML = '-'
            document.getElementById("5").innerHTML = '-'
            document.getElementById("6").innerHTML = '-'
            document.getElementById("7").innerHTML = '-'
            document.getElementById("8").innerHTML = '-'
            document.getElementById("9").innerHTML = '-'
            turn = 0
            X1 = false
            X2 = false
            X3 = false
            X4 = false
            X5 = false
            X6 = false
            X7 = false
            X8 = false
            X9 = false
            O1 = false
            O2 = false
            O3 = false
            O4 = false
            O5 = false
            O6 = false
            O7 = false
            O8 = false
            O9 = false
          }
    </script>
  <table>
    <tr>
      <td align="center"><button id="1" onclick="Xon1()">-</button></td>
      <td align="center"><button id="2" onclick="Xon2()">-</button></td>
      <td align="center"><button id="3" onclick="Xon3()">-</button></td>
    </tr>
    <tr>
      <td align="center"><button id="4" onclick="Xon4()">-</button></td>
      <td align="center"><button id="5" onclick="Xon5()">-</button></td> 
      <td align="center"><button id="6" onclick="Xon6()">-</button></td>
    </tr>
    <tr>
      <td align="center"><button id="7" onclick="Xon7()">-</button></td>
      <td align="center"><button id="8" onclick="Xon8()">-</button></td>
      <td align="center"><button id="9" onclick="Xon9()">-</button></td>
    </tr>
  </table>
  <button onclick="Restart()">Restart</button>
  <h4 id="win"></h4>
  </body>
</html>

So if you go to the far right middle square the the bottom right square it decides it’s just gonna cheat and place two O’s. I can’t figure out why. So if anyone can help me figure it out and or help clean up the code because I know it’s long and messy that would be great. I need to add more details not so tic-tac-toe ai cheating please help and the such. 🙂

How do I lower the version of ONNX in javascript?

I’ve been trying to integrate my ML model I trained in python and extract it as an ONNX file to my test website so I can try it but I can’t seem to run it. Looking at the console, it outputs this error.

opset.ts:48 Uncaught (in promise) TypeError: cannot resolve operator ‘LinearRegressor’ with opsets: ai.onnx.ml v1, ai.onnx v19

How do I fix this?

After searching for the error online, it seems like that my model isn’t fit to the version of ONNX I’m using?
<script src="https://cdn.jsdelivr.net/npm/onnxjs/dist/onnx.min.js"></script>

I did try to use [email protected] that fixed someones error which was similar to me but it just outputs the same error.

What is the point of re-rendering the compnonets that didn’t have change in their state in React?

I have the main component with a state and a static component inside. When the state changes, the main component is re-rendered, which makes complete sense, but the static component is re-rendered too.

import { useState } from 'react';

function StaticComponent (){
  console.log('re-rendering static component (why?)')

  return <i>Nothing non-static in here</i>
}

function App() {
  console.log('re-rendering App')
  const [state, setState] = useState(0)
  return (
    <>
      {state}<br />
      <button onClick={() => setState((state) => state + 1)}>+</button><br />
      <StaticComponent/>
    </>
  )
}

export default App

What’s the point of re-rendering the static component if there is no change in props or state? I came up with a workaround by writing it the following way (and it really worked, unexpectedly for me):

{useMemo(() => <StaticComponent/>, [])}

But it’s pretty obvious that this workaround is not the solution anyone would want to use. But why don’t React developers implement something similar for checking if there was a state change in a specific component before re-rendering it?

Error Message after just changing my SolrUrl to my local Solr server: resource was blocked due to MIME type mismatch

I just started using AJAX Solr to implement a demo from scratch.
(https://github.com/evolvingweb/ajax-solr/wiki/Reuters-tutorial%3A-step-1)

I built my local Solr data from reuter data downloaded from the tutorial link. I used Solr 9.4.0 to set up my local collection, reuterdata, and tested it in the Solr Admin.

The query worked fine in Solr Admin UI but after I started modifying my reuters.js file and changed solrUrl to my local Solr URL which is “http://localhost:8983/solr/reuterdata/”, it came across an error immediately. I only made this small change, and I did not touch any other codes. When I loaded the index.html from my local folder, I expected the reuter data from my local Solr can be loaded into the HTML page, but it didn’t show up. It only showed some h2 texts no contents under these h2 texts. I used firebug to debug the error. There was the following error:

“The resource from “http://localhost:8983/solr/reuterdata/select?facet=true&q=%3A&facet.field=topics&facet.field=organisations&facet.field=exchanges&facet.field=countryCodes&facet.limit=20&facet.mincount=1&f.topics.facet.limit=50&f.countryCodes.facet.limit=-1&facet.date=date&facet.date.start=1987-02-26T00%3A00%3A00.000Z%2FDAY&facet.date.end=1987-10-20T00%3A00%3A00.000Z%2FDAY%2B1DAY&facet.date.gap=%2B1DAY&json.nl=map&wt=json&json.wrf=jQuery172003692584046418779_1706919458200&_=1706919458231” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff).”

“Loading failed for the with source “http://localhost:8983/solr/reuterdata/select?facet=true&q=%3A&facet.field=topics&facet.field=organisations&facet.field=exchanges&facet.field=countryCodes&facet.limit=20&facet.mincount=1&f.topics.facet.limit=50&f.countryCodes.facet.limit=-1&facet.date=date&facet.date.start=1987-02-26T00%3A00%3A00.000Z%2FDAY&facet.date.end=1987-10-20T00%3A00%3A00.000Z%2FDAY%2B1DAY&facet.date.gap=%2B1DAY&json.nl=map&wt=json&json.wrf=jQuery172003692584046418779_1706919458200&_=1706919458231”.

My questions:

  1. Why was the resource from Solr blocked? Is that due to this new Solr version as I knew this AJAX-Solr was built many years ago and may not be compatible with new Solr version.
  2. Why can the scripts be loaded even though I didn’t change anything except the SolrUrl address?

Any replies will be appreciated. Thank you so much.

Transforming a complex graphic into an array or another data structure in JS/TS

Good evening,

I would like to create a tool that calculates the takeoff speeds required for a Boeing 747-400F. Being an avgeek myself, I have access to authentic documentation for the real aircraft.
this graphic graphic represents the climatic conditions and it is divided into regions (A,B,D..). By knowing the current temperature and airport elevation, you can determine which conditions you are in. (for example, region A)

Graphic with a lot of curves

After choosing a region (A for ex.) you move to this second table where you need to know the aircraft’s wheight, and after crossing it the region A, you can determine the takeoff speeds required : V1,VR,V2.

Table with takeoff speeds

It is easy to determine the takeoff speeds by reading these two charts, but my question is, how can I have the first graphic transformed into some sort of data structure that would allow me to use it in a Javascript or Typescript code.

Thank you for your time.

Javascript: Number with comma as decimal separator

Moodle is giving me a number with a comma as a decimal separator, i. g. 67,89.
It’s a number, not a string.

How can I convert this into a number with a dot as a decimal separator so i can use it with JS?

My main problem is to convert the number with all digits to a string.

Thank you very much.

How to prevent a page from reloading

I am working on an academic project where I am asked to create a modal window that displays a list of images that can be deleted by clicking on the trash icon above the image The requirements are that the page should not reload after deleting an image and the modal should not disappear Here is my HTML/CSS/JS code.
HTML code:

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Sophie Bluel - Architecte d'intérieur</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=Work+Sans&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
    crossorigin="anonymous" referrerpolicy="no-referrer">   
    <meta name="description" content="">
    <link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
    <!--Barre noir-->
    <div class="js-edition mask_barre_hidden">
        <i class="fa-regular fa-pen-to-square"></i>
        <p>  Mode édition</p>
    </div>
    <header>
        <h1>Sophie Bluel <span>Architecte d'intérieur</span></h1>
        <nav>
            <ul>
                <li class="nav_menu projects"><a href="#portfolio">projets</a></li>
                <li class="nav_menu contact"><a href="#contact">contact</a></li>
                <li class="nav_menu login"><a href="pages/login.html">login</a></li>
                <li class="nav_menu logout_hidden"><a href="index.html">logout</a></li>
                <li><a href="#"><img src="./assets/icons/instagram.png" alt="Instagram"></a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section id="introduction">
            <figure>
                <img src="./assets/images/sophie-bluel.png" alt="">
            </figure>
            <article>
                <h2>Designer d'espace</h2>
                <p>Je raconte votre histoire, je valorise vos idées. Je vous accompagne de la conception à la livraison finale du chantier.</p>
                <p>Chaque projet sera étudié en commun, de façon à mettre en valeur les volumes, les matières et les couleurs dans le respect de l’esprit des lieux et le choix adapté des matériaux. Le suivi du chantier sera assuré dans le souci du détail, le respect du planning et du budget.</p>
                <p>En cas de besoin, une équipe pluridisciplinaire peut-être constituée : architecte DPLG, décorateur(trice)</p>
            </article>
        </section>
        <section id="portfolio">
            <div class="edit_project">
                <h2>Mes Projets</h2>
                <div class="popup_edit">
                    <a href="#modal1" class="js-modal1 modify_action modify_hidden"><i class="fa-xs fa-solid fa-edit"></i> modifier</a>
                </div>
            </div>
            <div class="navigation">
                <a href="#" class="active nav_link tous">Tous</a>
                <a href="#" class="nav_link objets">Objets</a>
                <a href="#" class="nav_link appartements">Appartements</a>
                <a href="#" class="nav_link hotels_restaurants">Hôtels&restaurants</a>
            </div>
            <div class="gallery">
                
            </div>
        </section>
        <section id="contact">
            <h2>Contact</h2>
            <p>Vous avez un projet ? Discutons-en !</p>
            <form action="#" method="post">
                <label for="name">Nom</label>
                <input type="text" name="name" id="name">
                <label for="email">Email</label>
                <input type="email" name="email" id="email">
                <label for="message">Message</label>
                <textarea name="message" id="message" cols="30" rows="10"></textarea>
                <input type="submit" value="Envoyer">
            </form>
        </section>
    </main>

    <footer>
        <nav>
            <ul>
                <li>Mentions Légales</li>
            </ul>
        </nav>
    </footer>
    <aside id="modal1" class="modal" aria-hidden="true" role="dialog" aria-labelledby="titlemodal1" style="display:none;">
        <div class="modal-wrapper js-modal-stop">
            <div class="wrapper-nav">
                <a href="#" class="js-modal-close closed"><i class="fa-solid fa-xmark"></i></a>
            </div>
            <div class="wrapper-content">
                <div class="content-title modal1-title">
                    <h2 id="titlemodal1">Galerie photo</h2>
                </div>
                <div class="modal_gallery">
                    
                </div>
            </div>
            <hr><br>
            <div class="wrapper-link">
                <a href="#modal2" class="js-modal2 modal_submit">Ajouter une photo</a>
            </div>
        </div>
    </aside>
    <aside id="modal2" class="modal" role="dialog" aria-labelledby="titlemodal2" style="display:none;">
        <div class="modal-wrapper js-modal-stop">
            <div class="wrapper-nav">
                <a href="#" class="js-modal-close forward"><i class="fa-solid fa-arrow-left arow-link"></i></a>
                <a href="#" class="js-modal-close-all"><i class="fa-solid fa-xmark"></i></a>
            </div>
            <div class="wrapper-content">
                <div class="content-title">
                    <h2 id="titlemodal2">Ajout photo</h2>
                </div>
                <div id="notification"></div>
                    <form id="insert-photos" class="insert-photos form-img formulaire-work" method="post" enctype="multipart/form-data">
                    <div class="container-load">
                        <i class="fa-solid fa-light fa-image logo-load"></i>
                        <label id="btn-ajout-photo" for="imageUpload" class="input-label">+ Ajouter photo</label>
                        <input type="file" id="imageUpload" name="imageUpload" accept=".jpg, .png" class="input-file">
                        <p class="file-types">jpg, png : 4mo max</p>
                    </div>
                    <label for="name">Titre</label>
                    <input type="text" name="title" id="title">
                    <label for="category">Catégorie</label>
                    <select name="category" id="category">
                        <option value="1">Objets</option>
                        <option value="2">Appartements</option>
                        <option value="3">Hôtels & Restaurants</option>
                    </select>                    
                    <hr>
                    <input type="submit" value="Valider" class="insert-work">
                </form>                
            </div>
        </div>
    </aside>
    <script src="assets/js/script.js"></script>
    <script src="assets/js/modal.js"></script>
</body>
</html>

this my css code:

// Récupération des fiches eventuellement stockées dans le sessionStorage
let works = window.sessionStorage.getItem("works");

links = {
    "tous": "Tous",
    "objets": "Objets",
    "appartements": "Appartements",
    "hotels_restaurants": "Hotels & restaurants"
}

// Récupération des travaux depuis l'API
const sectionWorks = document.querySelector(".gallery");
works = fetch('http://localhost:5678/api/works')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        // Afficher par defaut toutes les données sur les travaux
        defaultData(data);
        // Récupération des liens de navigation
        const links = document.querySelectorAll(".nav_link");
        var all = document.querySelectorAll("tous");
        console.log(links[1].classList[1])
        // Ajout d'un gestionnaire d'événements click à chaque lien
        links.forEach(link => {
            console.log(link.classList[1])
            link.addEventListener("click", function (event) {
                event.preventDefault();
                // Retirer la classe active de tous les liens tous
                for (let j = 0; j < links.length; j++) {
                    links[j].className = links[j].className.replace(" active", "");
                    links[j].classList.remove("active");
                }                
                // Nous recuperons chaque categorie en fonction de sa clé
                const category = getCategoryByKey(link.classList[1]);
                // Ajouter la classe active au lien cliqué
                this.className += " active";
                // Effectuons les conditions sur les catégories
                if (category === "Tous") {
                    fetchData(data, null);
                } else {
                    fetchData(data, category);
                }
            });
        });
    });


// fonction qui prend la class comme clé et retourne la categorie correspondante
// dans le tableau links, tableau qui fait la correspondance 
// entre la class et la categorie    
function getCategoryByKey(key) {
    if (key in links) {
        return links[key];
    } else {
        return null;
    }
}

// function qui prend une chaine et la met la première lettre
// en majuscule
function capitalize(myString) {
    const capitalizedString = myString.charAt(0).toUpperCase() + myString.slice(1);
    return capitalizedString;
}

// function permet de retourner les données de l'API en fonction
// de la categorie qui lui est passée
async function fetchData(data, category) {
    let filteredData;
    if (category !== null) {
        filteredData = data.filter(item => item.category.name === category);
    } else {
        filteredData = data
    }

    // Récupération de l'élément du DOM qui accueillera les travaux
    const sectionWorks = document.querySelector(".gallery");

    // Suppression des travaux existants
    sectionWorks.innerHTML = "";

    // Création d'une balise dédiée à chaque travail
    filteredData.forEach(item => {
        const workElement = document.createElement("figure");
        // On crée l’élément img.
        const imageElement = document.createElement("img");
        // On accède à l’indice i de la liste des travaux pour configurer la source de l’image.
        imageElement.src = item.imageUrl;
        // Idem pour le titre 
        const figcaptionElement = document.createElement("figcaption");
        figcaptionElement.innerHTML = item.title;
        // On rattache la balise figure à la section gallery
        sectionWorks.appendChild(workElement);
        // On rattache l’image à workElement (la balise figure)
        workElement.appendChild(imageElement);
        workElement.appendChild(figcaptionElement);
    });
}

// fonction qui affiche la liste de travaux par défaut sur la page d'acceuille
async function defaultData(data) {
    for (let i = 0; i < data.length; i++) {
        // Récupération de l'élément du DOM qui accueillera les travaux
        const sectionWorks = document.querySelector(".gallery");
        // Création d’une balise dédiée à un travail
        const workElement = document.createElement("figure");
        // On crée l’élément img.
        const imageElement = document.createElement("img");
        // On accède à l’indice i de la liste destravaux pour configurer la source de l’image.
        imageElement.src = data[i].imageUrl;
        // Idem pour le nom ... 
        const figcaptionElement = document.createElement("figcaption");
        figcaptionElement.innerHTML = data[i].title;
        // On rattache la balise figure à la section gallery
        sectionWorks.appendChild(workElement);
        // On rattache l’image à workElement
        workElement.appendChild(imageElement);
        workElement.appendChild(figcaptionElement);
    }
    return sectionWorks
}  

// Fonction pour vérifier l'état de connexion
function checkLoginStatus() {
    const login_value = document.querySelector(".nav_menu.login");
    const logout_value = document.querySelector(".nav_menu.logout_hidden");
    const modify_action = document.querySelector(".js-modal1.modify_action");
    const js_edition = document.querySelector(".js-edition.mask_barre_hidden");
    
    if(localStorage.getItem("auth")) {
        // Si l'utilisateur est connecté
        logout_value.classList.remove("logout_hidden");
        modify_action.classList.remove("modify_hidden");
        js_edition.classList.remove("mask_barre_hidden");
        login_value.classList.add("login_hidden");
    } else {
        // Si l'utilisateur n'est pas connecté
        login_value.classList.remove("login_hidden");
        modify_action.classList.add("modify_hidden");
        logout_value.classList.add("logout_hidden");
        js_edition.classList.add("mask_barre_hidden");
    }
}

// Appeler la fonction chaque fois que la page est chargée
window.onload = checkLoginStatus;

// Ajouter un écouteur d'événements pour le bouton de déconnexion
const logout = document.querySelector(".nav_menu.logout_hidden");
logout.addEventListener("click", function (event) {
    //event.preventDefault();
    // event.stopPropagation(); // Empêche la propagation de l'événement
    localStorage.clear();
    checkLoginStatus();
    window.location.href = "../index.html"; // Redirige vers la page d'accueil
});

document.addEventListener("DOMContentLoaded", function() {
    const listOfWorks = document.querySelector(".modal_gallery");
    fetch('http://localhost:5678/api/works')
        .then(response => response.json())
        .then(data => {
            console.log('data', data);
            modalData(data);
        });

    async function modalData(data) {
        data.forEach((item, i) => {
            item = item;
            const workElement = document.createElement("figure");
            workElement.classList.add('work-element');
            workElement.dataset.id = item.id; // Ajoutez l'ID de l'élément à l'attribut data-id

            const imageElement = document.createElement("img");
            imageElement.src = item.imageUrl;
            imageElement.style.width = "76.86px";
            imageElement.style.height = "102.57px";

            const trashIcon = document.createElement("i");
            trashIcon.classList.add('fa-regular', 'fa-trash-can', 'trash-icon');

            const linkIcon = document.createElement("a");
            linkIcon.href = "javascript:void(0)";
            linkIcon.classList.add('link-icon');
            linkIcon.appendChild(trashIcon);
            
            linkIcon.addEventListener('click', async (e) => {
                e.preventDefault();
                e.stopPropagation(); // Empêche la propagation de l'événement
                const response = await deleteEntryFromDatabase(item, e);
                if (response.ok) { // vérifiez que la suppression a réussi
                    e.currentTarget.parentNode.remove(); // supprime l'élément du DOM
                } else {
                    console.error('Erreur lors de la suppression du projet');
                }
            });
                        
            const figcaptionElement = document.createElement("figcaption");
            figcaptionElement.style.fontSize = "14px";

            listOfWorks.appendChild(workElement); // Utilisez listOfWorks au lieu de sectionWorks
            workElement.appendChild(imageElement);
            workElement.appendChild(linkIcon);
            workElement.appendChild(figcaptionElement);
        });
    }        
});

async function deleteEntryFromDatabase(item, e) {
    e.preventDefault();

    console.log('item: ', item);
    var token = window.localStorage.getItem("token")
    console.log(JSON.stringify(token))
   
    const response = await fetch(`http://localhost:5678/api/works/${item.id}`, {
        method: 'DELETE',
        headers: new Headers({
            'Authorization': 'Bearer ' + token
        })
    });    
    if (!response.ok) {
        throw new Error('Erreur lors de la suppression du projet');
    }else{ // vérifiez que la suppression a réussi
        e.target.parentNode.remove(); // supprime l'élément du DOM
    }

    window.sessionStorage.removeItem("works")    
}

function deleteDomElement(item) {
    const element = document.querySelector(`[data-id="${item.id}"]`);
    if (element) {
        element.remove();
    }
}

the modal.js file:

// Déclaration de deux variables globales modal1 et modal2 initialisées à null
let modal1 = null
let modal2 = null

// Fonction asynchrone permettant d'ouvrir la première modale
const openModal1 = async function (e) {
    e.preventDefault() // Empêche l'action par défaut de l'événement
    // Sélectionne l'élément cible
    const target = document.querySelector(e.target.getAttribute('href'))
    // Réinitialise la propriété d'affichage
    target.style.display = null
    // Supprime l'attribut 'aria-hidden'
    target.removeAttribute('aria-hidden')
    // Ajoute l'attribut 'aria-modal' avec la valeur 'true'
    target.setAttribute('aria-modal', 'true') 
    // Affecte l'élément cible à la variable modal1
    modal1 = target 
    // Ajoute un écouteur d'événement 'click' qui appelle la fonction closeModal1
    // modal1.addEventListener('click', closeModal1) 
    // Ajoute un écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-close' qui appelle la fonction closeModal1
    modal1.querySelector('.js-modal-close').addEventListener('click', closeModal1) 
    // Ajoute un écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-stop' qui appelle la fonction stopPropagation
    modal1.querySelector('.js-modal-stop').addEventListener('click', stopPropagation) 
}

// Fonction permettant de fermer la première modale
const closeModal1 = function (e) {
    if (modal1 === null) return // Si modal1 est null, la fonction s'arrête
    // Empêche l'action par défaut de l'événement
    e.preventDefault()
    // Change la propriété d'affichage à 'none'
    modal1.style.display = "none" 
    // Ajoute l'attribut 'aria-hidden' avec la valeur 'true'
    modal1.setAttribute('aria-hidden', 'true')
    // Supprime l'attribut 'aria-modal'
    modal1.removeAttribute('aria-modal') 
    // Supprime l'écouteur d'événement 'click' qui appelle la fonction closeModal1
    modal1.removeEventListener('click', closeModal1) 
    // Supprime l'écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-close' qui appelle la fonction closeModal1
    modal1.querySelector('.js-modal-close').removeEventListener('click', closeModal1)
    // Supprime l'écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-stop' qui appelle la fonction stopPropagation
    modal1.querySelector('.js-modal-stop').removeEventListener('click', stopPropagation) 
    // Réinitialise la variable modal1 à null
    modal1 = null
}

// Evenement de click pour lancer la modal1
document.querySelectorAll('.js-modal1').forEach(a => {
    a.addEventListener('click', openModal1)

})


// Fonction asynchrone permettant d'ouvrir la deuxième modale
const openModal2 = async function (e) {
    // Empêche l'action par défaut de l'événement
    e.preventDefault()
    // Sélectionne l'élément cible
    const target = document.querySelector(e.target.getAttribute('href'))
    // Réinitialise la propriété d'affichage
    target.style.display = null
    // Supprime l'attribut 'aria-hidden'
    target.removeAttribute('aria-hidden')
    // Ajoute l'attribut 'aria-modal' avec la valeur 'true'
    target.setAttribute('aria-modal', 'true')
    // Affecte l'élément cible à la variable modal2
    modal2 = target
    // Ajoute un écouteur d'événement 'click' qui appelle la fonction closeModal2
    // modal2.addEventListener('click', closeModal2)
    // Ajoute un écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-close' qui appelle la fonction closeModal2
    modal2.querySelector('.js-modal-close').addEventListener('click', closeModal2) 
    // Ajoute un écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-stop' qui appelle la fonction stopPropagation
    modal2.querySelector('.js-modal-stop').addEventListener('click', stopPropagation) 
}

// Fonction permettant de fermer la deuxième modale
const closeModal2 = function (e) {
    if (modal2 === null) return // Si modal2 est null, la fonction s'arrête
    e.preventDefault() // Empêche l'action par défaut de l'événement
    modal2.style.display = "none" // Change la propriété d'affichage à 'none'
    // Ajoute l'attribut 'aria-hidden' avec la valeur 'true'
    modal2.setAttribute('aria-hidden', 'true')
    // Supprime l'attribut 'aria-modal' 
    modal2.removeAttribute('aria-modal')
    // Supprime l'écouteur d'événement 'click' qui appelle la fonction closeModal2
    modal2.removeEventListener('click', closeModal2) 
    // Supprime l'écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-close' qui appelle la fonction closeModal2
    modal2.querySelector('.js-modal-close').removeEventListener('click', closeModal2)
    // Supprime l'écouteur d'événement 'click' sur l'élément avec la classe '.js-modal-stop' qui appelle la fonction stopPropagation
    modal2.querySelector('.js-modal-stop').removeEventListener('click', stopPropagation) 
    modal2 = null // Réinitialise la variable modal2 à null
}

// Evenement de click pour lancer la modal2
document.querySelectorAll('.js-modal2').forEach(a => {
    a.addEventListener('click', openModal2)

})

// fonction permettant de fermer toutes les fenêtres modales
const closeAllModals = function (e) {
    e.preventDefault() // Empêche l'action par défaut de l'événement
    if (modal1 !== null) closeModal1(e) // Si modal1 n'est pas null, appelle la fonction closeModal1
    if (modal2 !== null) closeModal2(e) // Si modal2 n'est pas null, appelle la fonction closeModal2
}

// Evenement de click pour fermer toutes les fenêtres modales
document.querySelectorAll('.js-modal-close-all').forEach(a => {
    a.addEventListener('click', closeAllModals)
})

const stopPropagation = function (e) {
    e.stopPropagation()
}

//Ajout de photo à la galerie
// Récupération du formulaire
const insertPhotoForm = document.getElementById("insert-photos");

// Récupération des éléments du formulaire
const title = document.getElementById("title");
const category = document.getElementById("category");
const imageUpload = document.getElementById("imageUpload");
const submitButton = document.querySelector(".insert-work");

// Fonction pour vérifier si tous les champs sont remplis
function checkForm() {
    // Si le champ 'title', 'category' sont remplis et un fichier est téléchargé pour 'imageUpload'
    if (title.value && category.value && imageUpload.files.length > 0) {
        console.log(submitButton); // Affiche l'objet 'submitButton' dans la console
        submitButton.id = "btn-active-work"; // Change l'id de 'submitButton' à 'btn-active-work'
    } else {
        // Si les conditions ne sont pas remplies, réinitialise l'id de 'submitButton'
        submitButton.id = ""; 
    }
}


// Ajout des écouteurs d'événements
title.addEventListener("input", checkForm);
category.addEventListener("change", checkForm);
imageUpload.addEventListener("change", checkForm);

// Ajoute un écouteur d'événement 'change' à l'élément avec l'id 'insert-photos'
document.getElementById('insert-photos').addEventListener('change', function(e) {
    var file = e.target.files[0]; // Récupère le premier fichier téléchargé
    var reader = new FileReader(); // Crée un nouvel objet FileReader
    reader.onloadend = function() { // Définit une fonction à exécuter lorsque la lecture du fichier est terminée
        var img = document.createElement('img'); // Crée un nouvel élément img
        img.src = reader.result; // Définit l'attribut src de l'élément img avec le résultat de la lecture du fichier
        var container = document.querySelector('.container-load'); // Sélectionne l'élément avec la classe '.container-load'
        container.innerHTML = ''; // Vide le contenu HTML de l'élément container
        container.appendChild(img); // Ajoute l'élément img à l'élément container
    }
    if (file) { // Si un fichier a été téléchargé
        reader.readAsDataURL(file); // Lit le fichier comme une URL de données
    }
});

// Ajout de l'événement 'submit' au formulaire
insertPhotoForm.addEventListener("submit", async (event) => {
    event.preventDefault();
    const dataAjout = new FormData();
    if (title.value && category.value && imageUpload.files[0]) {
        // Création d'un objet FormData pour stocker les données du formulaire
        dataAjout.append("title", title.value);
        dataAjout.append("category", Number(category.value));
        dataAjout.append("image", imageUpload.files[0]);
        submitButton.classList.add("btn-active-work"); // Utilisez submitButton ici
    }

    token = window.localStorage.getItem("token")
    // Effectuer la requête POST
    const response = await fetch("http://localhost:5678/api/works", {
        method: "POST",
        headers: {
            'Authorization': 'Bearer ' + token
        },
        body: dataAjout,
    });

    // Vérification de la réponse
    if (!response.ok) {
        const errorDetails = await response.text();
        throw new Error(`HTTP error! status: ${response.status}, details: ${errorDetails}`);
    } else {
        // Si la requête a réussi, on peut réinitialiser le formulaire et fermer la modale
        document.getElementById("title").value = "";
        document.getElementById("category").value = "Objets";
        document.getElementById("modal2").style.display = "none";
    }
});

if you want more detail or specification in the projet, you have the to the github projet: https://github.com/amoungui/portfolio-architecte-sophie-blue

Ajax post in the js File

I have a problem on the javascript..

Normaly i did maybe 100 times on the footer page jquery and ajax post.. But this time i have to do that in the javascript file..

Im very bad at jsript and jquery.

i have a file like this :

/*
Template Name: Velzon - Admin & Dashboard Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: [email protected]
File: Tasks-list init js
*/

var checkAll = document.getElementById("checkAll");
if (checkAll) {
  checkAll.onclick = function () {
    var checkboxes = document.querySelectorAll('.form-check-all input[type="checkbox"]');
    var checkedCount = document.querySelectorAll('.form-check-all input[type="checkbox"]:checked').length;
    for (var i = 0; i < checkboxes.length; i++) {
      checkboxes[i].checked = this.checked;
      if (checkboxes[i].checked) {
          checkboxes[i].closest("tr").classList.add("table-active");
      } else {
          checkboxes[i].closest("tr").classList.remove("table-active");
      }
    }

    (checkedCount > 0) ? document.getElementById("remove-actions").style.display = 'none' : document.getElementById("remove-actions").style.display = 'block';
  };
}
var perPage = 8;
var editlist = false;

//Table
var options = {
    valueNames: [
        "id",
        "project_name",
        "tasks_name",
        "client_name",
        "assignedto",
        "due_date",
        "status",
        "priority",
    ],
    page: perPage,
    pagination: true,
    plugins: [
        ListPagination({
            left: 2,
            right: 2,
        }),
    ],
};

// Init list
var tasksList = new List("tasksList", options).on("updated", function (list) {
    list.matchingItems.length == 0 ?
        (document.getElementsByClassName("noresult")[0].style.display = "block") :
        (document.getElementsByClassName("noresult")[0].style.display = "none");
    var isFirst = list.i == 1;
    var isLast = list.i > list.matchingItems.length - list.page;
    // make the Prev and Nex buttons disabled on first and last pages accordingly
    document.querySelector(".pagination-prev.disabled") ?
        document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
    document.querySelector(".pagination-next.disabled") ?
        document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
    if (isFirst)
        document.querySelector(".pagination-prev").classList.add("disabled");
    if (isLast)
        document.querySelector(".pagination-next").classList.add("disabled");
    if (list.matchingItems.length <= perPage)
        document.querySelector(".pagination-wrap").style.display = "none";
    else
        document.querySelector(".pagination-wrap").style.display = "flex";
    if (list.matchingItems.length == perPage)
        document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
    if (list.matchingItems.length > 0)
        document.getElementsByClassName("noresult")[0].style.display = "none";
    else
        document.getElementsByClassName("noresult")[0].style.display = "block";
});

const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
    var json_records = JSON.parse(this.responseText);
    Array.from(json_records).forEach(function (raw) {

        var assignedElem = raw.assignedto;
        var showElem = 3;
        var imgHtml = '<div class="avatar-group flex-nowrap">';
        Array.from(assignedElem.slice(0, showElem)).forEach(function (img) {
            imgHtml += '<a href="javascript: void(0);" class="avatar-group-item" data-img="' + img.assigneeImg + '"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="'+img.assigneeName+'">
                <img src="'+ img.assigneeImg + '" alt="" class="rounded-circle avatar-xxs" />
            </a>';
        });
        if(assignedElem.length > showElem){
            var elemLength = assignedElem.length - showElem;
            imgHtml += '<a href="javascript: void(0);" class="avatar-group-item"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="'+elemLength+' More">
            <div class="avatar-xxs">
            <div class="avatar-title rounded-circle">'+elemLength+'+</div>
            </div>
        </a>'
        }
        imgHtml += '</div>';

        tasksList.add({
            id: '<a href="apps-tasks-details.php" class="fw-medium link-primary">#VLZ' + raw.id + "</a>",
            project_name: '<a href="apps-projects-overview.php" class="fw-medium link-primary">' + raw.project_name + "</a>",
            tasks_name: raw.tasks_name,
            client_name: raw.client_name,
            due_date: raw.due_date,
            status: isStatus(raw.status),
            priority: isPriority(raw.priority)
        });
        tasksList.sort('id', { order: "asc" });
        refreshCallbacks();
        tooltipElm();
    });
    tasksList.remove("id", `<a href="apps-tasks-details.php" class="fw-medium link-primary">#VLZ501</a>`);
}
xhttp.open("GET", "liste.php");
xhttp.send();

isCount = new DOMParser().parseFromString(
    tasksList.items.slice(-1)[0]._values.id,
    "text/html"
);

var isValue = isCount.body.firstElementChild.innerHTML;

var idField = document.getElementById("tasksId"),
    projectNameField = document.getElementById("projectName-field"),
    tasksTitleField = document.getElementById("tasksTitle-field"),
    clientNameField = document.getElementById("clientName-field"),
    assignedtoNameField = 'Demo Assign', //document.getElementById("assignedtoName-field"),
    dateDueField = document.getElementById("duedate-field"),
    priorityField = document.getElementById("priority-field"),
    statusField = document.getElementById("ticket-status"),
    addBtn = document.getElementById("add-btn"),
    editBtn = document.getElementById("edit-btn"),
    removeBtns = document.getElementsByClassName("remove-item-btn"),
    editBtns = document.getElementsByClassName("edit-item-btn");
refreshCallbacks();
//filterOrder("All");

function tooltipElm(){
    var tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
    var tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
}

function filterOrder(isValue) {
    var values_status = isValue;
    tasksList.filter(function (data) {
        var statusFilter = false;
        matchData = new DOMParser().parseFromString(
            data.values().status,
            "text/html"
        );
        var status = matchData.body.firstElementChild.innerHTML;
        if (status == "All" || values_status == "All") {
            statusFilter = true;
        } else {
            statusFilter = status == values_status;
        }
        return statusFilter;
    });
    tasksList.update();
}

function formadd () {
    $.ajax({
        url:"add.php",
        method:"POST",
        data:$(this).serialize(),
        success:function(data)
        {
            alert("Ok");
        }
    });
}
function updateList() {
    var values_status = document.querySelector(
        "input[name=status]:checked"
    ).value;

    data = userList.filter(function (item) {
        var statusFilter = false;

        if (values_status == "All") {
            statusFilter = true;
        } else {
            statusFilter = item.values().sts == values_status;
        }
        return statusFilter;
    });

    userList.update();
}

document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
    if (e.relatedTarget.classList.contains("edit-item-btn")) {
        document.getElementById("exampleModalLabel").innerHTML = "Edit Task";
        document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
        document.getElementById("add-btn").innerHTML = "Update";
    } else if (e.relatedTarget.classList.contains("add-btn")) {
        document.getElementById("exampleModalLabel").innerHTML = "Add Task";
        document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
        document.getElementById("add-btn").innerHTML = "Add Task";
    } else {
        document.getElementById("exampleModalLabel").innerHTML = "List Task";
        document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
    }
});

document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
    clearFields();
});

document.querySelector("#tasksList").addEventListener("click", function () {
    ischeckboxcheck();
});

var table = document.getElementById("tasksTable");
// save all tr
var tr = table.getElementsByTagName("tr");
var trlist = table.querySelectorAll(".list tr");

var count = 11;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
    form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
            event.preventDefault();
            event.stopPropagation();
        } else {
            event.preventDefault();
            
            if (
                projectNameField.value !== "" &&
                tasksTitleField.value !== "" &&
                clientNameField.value !== "" &&
                dateDueField.value !== "" &&
                priorityField.value !== "" &&
                statusField.value !== "" && !editlist
            ) {
                tasksList.add({
                    id: '<a href="apps-tasks-details.php" class="fw-medium link-primary">#VLZ'+count+"</a>",
                    project_name: '<a href="apps-projects-overview.php" class="fw-medium link-primary">'+projectNameField.value+"</a>",
                    tasks_name: tasksTitleField.value,
                    client_name: clientNameField.value,
                    assignedto: assignToUsers(),
                    due_date: fomateDate(dateDueField.value),
                    status: isStatus(statusField.value),
                    priority: isPriority(priorityField.value)
                });
                
                formadd();
                tasksList.sort('id', { order: "desc" });
                document.getElementById("close-modal").click();
                
                clearFields();
                refreshCallbacks();
                tooltipElm();
                count++;
                Swal.fire({
                    position: 'center',
                    icon: 'success',
                    title: 'Task inserted successfully!',
                    showConfirmButton: false,
                    timer: 2000,
                    showCloseButton: true
                });
            } else if (
                projectNameField.value !== "" &&
                tasksTitleField.value !== "" &&
                clientNameField.value !== "" &&
                dateDueField.value !== "" &&
                priorityField.value !== "" &&
                statusField.value !== "" && editlist
            ) {
                var editValues = tasksList.get({
                    id: idField.value,
                });
                Array.from(editValues).forEach(function (x) {
                    isid = new DOMParser().parseFromString(x._values.id, "text/html");
                    var selectedid = isid.body.firstElementChild.innerHTML;
                    if (selectedid == itemId) {
                        x.values({
                            id: '<a href="javascript:void(0);" class="fw-medium link-primary">'+idField.value+"</a>",
                            project_name: '<a href="apps-projects-overview.php" class="fw-medium link-primary">' +projectNameField.value+"</a>",
                            tasks_name: tasksTitleField.value,
                            client_name: clientNameField.value,
                            assignedto: assignToUsers(),
                            due_date: fomateDate(dateDueField.value),
                            status: isStatus(statusField.value),
                            priority: isPriority(priorityField.value)
                        });
                    }
                });
                document.getElementById("close-modal").click();
                clearFields();
                tooltipElm();
                Swal.fire({
                    position: 'center',
                    icon: 'success',
                    title: 'Task updated Successfully!',
                    showConfirmButton: false,
                    timer: 2000,
                    showCloseButton: true
                });
            }
        }
    }, false)
})


var example = new Choices(priorityField, {
    searchEnabled: false,
});

var statusVal = new Choices(statusField, {
    searchEnabled: false,
});

function SearchData() {
    var isstatus = document.getElementById("idStatus").value;
    var pickerVal = document.getElementById("demo-datepicker").value;

    var date1 = pickerVal.split(" to ")[0];
    var date2 = pickerVal.split(" to ")[1];

    tasksList.filter(function (data) {
        matchData = new DOMParser().parseFromString(
            data.values().status,
            "text/html"
        );
        var status = matchData.body.firstElementChild.innerHTML;
        var statusFilter = false;
        var dateFilter = false;

        if (status == "all" || isstatus == "all") {
            statusFilter = true;
        } else {
            statusFilter = status == isstatus;
        }

        if (
            new Date(data.values().due_date.slice(0, 12)) >= new Date(date1) &&
            new Date(data.values().due_date.slice(0, 12)) <= new Date(date2)
        ) {
            dateFilter = true;
        } else {
            dateFilter = false;
        }

        if (statusFilter && dateFilter) {
            return statusFilter && dateFilter;
        } else if (statusFilter && pickerVal == "") {
            return statusFilter;
        } else if (dateFilter && pickerVal == "") {
            return dateFilter;
        }
    });
    tasksList.update();
}

function ischeckboxcheck() {
    Array.from(document.getElementsByName("chk_child")).forEach(function (x) {
        x.addEventListener("change", function (e) {
            if (x.checked == true) {
                e.target.closest("tr").classList.add("table-active");
            } else {
                e.target.closest("tr").classList.remove("table-active");
            }
  
            var checkedCount = document.querySelectorAll('[name="chk_child"]:checked').length;
            if (e.target.closest("tr").classList.contains("table-active")) {
                (checkedCount > 0) ? document.getElementById("remove-actions").style.display = 'block': document.getElementById("remove-actions").style.display = 'none';
            } else {
                (checkedCount > 0) ? document.getElementById("remove-actions").style.display = 'block': document.getElementById("remove-actions").style.display = 'none';
            }
        });
    });
}

function refreshCallbacks() {
    if (removeBtns){
        Array.from(removeBtns).forEach(function (btn) {
            btn.addEventListener("click", function (e) {
                e.target.closest("tr").children[1].innerText;
                itemId = e.target.closest("tr").children[1].innerText;
                var itemValues = tasksList.get({
                    id: itemId,
                });
    
                Array.from(itemValues).forEach(function (x) {
                    deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
                    var isElem = deleteid.body.firstElementChild;
                    var isdeleteid = deleteid.body.firstElementChild.innerHTML;
    
                    if (isdeleteid == itemId) {
                        document.getElementById("delete-record").addEventListener("click", function () {
                            tasksList.remove("id", isElem.outerHTML);
                            document.getElementById("deleteRecord-close").click();
                        });
                    }
                });
            });
        });
    }
    
    if (editBtns){
    Array.from(editBtns).forEach(function (btn) {
        btn.addEventListener("click", function (e) {
            e.target.closest("tr").children[1].innerText;
            itemId = e.target.closest("tr").children[1].innerText;
            var itemValues = tasksList.get({
                id: itemId,
            });

            Array.from(itemValues).forEach(function (x) {
                isid = new DOMParser().parseFromString(x._values.id, "text/html");
                var selectedid = isid.body.firstElementChild.innerHTML;
                if (selectedid == itemId) {
                    editlist = true;
                    idField.value = selectedid;

                    project = new DOMParser().parseFromString(x._values.project_name, "text/html");
                    var projectName = project.body.firstElementChild.innerHTML;
                    statusVal.setChoiceByValue(statusSelec);

                    projectNameField.value = projectName;
                    tasksTitleField.value = x._values.tasks_name;
                    clientNameField.value = x._values.client_name;
                    dateDueField.value = x._values.due_date;

                    Array.from(document.querySelectorAll('input[name="assignedTo[]"]')).forEach(function (subElem) {
                        var checkedElem = subElem.parentElement;
                        var nameelem = checkedElem.querySelector(".flex-grow-1").innerHTML;

                        var assignElem = new DOMParser().parseFromString(x._values.assignedto, "text/html");
                        assignElem.querySelectorAll(".avatar-group .avatar-group-item").forEach(function(item){
                            if(item.getAttribute('data-bs-title') == nameelem){
                                subElem.checked = true;
                            };
                        });
                    });

                    if (statusVal) statusVal.destroy();
                    statusVal = new Choices(statusField, {
                        searchEnabled: false
                    });
                    val = new DOMParser().parseFromString(x._values.status, "text/html");
                    var statusSelec = val.body.firstElementChild.innerHTML;
                    statusVal.setChoiceByValue(statusSelec);

                    if (example) example.destroy();
                    example = new Choices(priorityField, {
                        searchEnabled: false
                    });
                    val = new DOMParser().parseFromString(x._values.priority, "text/html");
                    var selected = val.body.firstElementChild.innerHTML;
                    example.setChoiceByValue(selected);
                    //priorityField.value = x._values.priority;

                    flatpickr("#duedate-field", {
                        dateFormat: "d M, Y",
                        defaultDate: x._values.due_date,
                    });
                }
            });
        });
    });
}

}

function clearFields() {
    projectNameField.value = "";
    tasksTitleField.value = "";
    clientNameField.value = "";
    assignedtoNameField.value = "";
    dateDueField.value = "";

    document.querySelectorAll('input[name="assignedTo[]"]').forEach(function(item){
        item.checked = false;
    });

    if (example)
        example.destroy();
    example = new Choices(priorityField);

    if (statusVal)
        statusVal.destroy();
    statusVal = new Choices(statusField);
}

document.querySelector(".pagination-next").addEventListener("click", function () {
    document.querySelector(".pagination.listjs-pagination") ?
        document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
        document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});

document.querySelector(".pagination-prev").addEventListener("click", function () {
    document.querySelector(".pagination.listjs-pagination") ?
        document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
        document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});

function isStatus(val) {
    switch (val) {
        case "Pending":
            return ('<span class="badge bg-warning-subtle text-warning text-uppercase">' + val + "</span>");
        case "Inprogress":
            return ('<span class="badge bg-secondary-subtle text-secondary text-uppercase">' + val + "</span>");
        case "Completed":
            return ('<span class="badge bg-success-subtle text-success text-uppercase">' + val + "</span>");
        case "New":
            return ('<span class="badge bg-info-subtle text-info text-uppercase">' + val + "</span>");
    }
}

function isPriority(val) {
    switch (val) {
        case "High":
            return ('<span class="badge bg-danger text-uppercase">' + val + "</span>");
        case "Low":
            return ('<span class="badge bg-success text-uppercase">' + val + "</span>");
        case "Medium":
            return ('<span class="badge bg-warning text-uppercase">' + val + "</span>");
    }
}

function fomateDate(date) {
    var dateObj = new Date(date);
    var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dateObj.getMonth()];
    return dateObj.getDate() + ' ' + month + ', ' + dateObj.getFullYear();
}

function assignToUsers() {
    var assignedtousers = [];
    var assignedTo =  document.querySelectorAll('input[name="assignedTo[]"]:checked');
    Array.from(assignedTo).forEach(function (ele) {
        var checkedElem = ele.parentElement;
        var imgpath = checkedElem.querySelector(".avatar-xxs").getAttribute('src');
        var namepath = checkedElem.querySelector(".flex-grow-1").innerHTML;
        var obj = {};
        obj["assigneeName"] = namepath
        obj["assigneeImg"] = imgpath
        assignedtousers.push(obj);
    });

    var assignedElem = assignedtousers;
    var showElem = 3;
    var imgHtml = '<div class="avatar-group flex-nowrap">';
    Array.from(assignedElem.slice(0, showElem)).forEach(function (img) {
        imgHtml += '<a href="javascript: void(0);" class="avatar-group-item" data-img="' + img.assigneeImg + '"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="'+img.assigneeName+'">
            <img src="'+ img.assigneeImg + '" alt="" class="rounded-circle avatar-xxs" />
        </a>';
    });
    if(assignedElem.length > showElem){
        var elemLength = assignedElem.length - showElem;
        imgHtml += '<a href="javascript: void(0);" class="avatar-group-item"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="'+elemLength+' More">
        <div class="avatar-xxs">
        <div class="avatar-title rounded-circle">'+elemLength+'+</div>
        </div>
    </a>'
    }
    imgHtml += '</div>';
    return imgHtml;
}

function deleteMultiple() {
    ids_array = [];
    var items = document.getElementsByName('chk_child');
    for (i = 0; i < items.length; i++) {
        if (items[i].checked == true) {
            var trNode = items[i].parentNode.parentNode.parentNode;
            var id = trNode.querySelector("td a").innerHTML;
            ids_array.push(id);
        }
    }
    if (typeof ids_array !== 'undefined' && ids_array.length > 0) {
        Swal.fire({
            title: "Are you sure?",
            text: "You won't be able to revert this!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonClass: 'btn btn-primary w-xs me-2 mt-2',
            cancelButtonClass: 'btn btn-danger w-xs mt-2',
            confirmButtonText: "Yes, delete it!",
            buttonsStyling: false,
            showCloseButton: true
        }).then(function (result) {
            if (result.value) {
                for (i = 0; i < ids_array.length; i++) {
                    tasksList.remove("id", `<a href="apps-tasks-details.php" class="fw-medium link-primary">${ids_array[i]}</a>`);
                }
                document.getElementById("remove-actions").style.display = 'none';
                document.getElementById("checkAll").checked = false;
                Swal.fire({
                    title: 'Deleted!',
                    text: 'Your data has been deleted.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-info w-xs mt-2',
                    buttonsStyling: false
                });
            }
        });
        document.getElementById('checkAll').checked = false;
    } else {
        Swal.fire({
            title: 'Please select at least one checkbox',
            confirmButtonClass: 'btn btn-info',
            buttonsStyling: false,
            showCloseButton: true
        });
    }
}

When form submit all details are adding table. But i have to save this data and i have to send to php file. i made in the script formadd function but it doesnt work.. i think i have to text diffirent..

i tryed diffirent ways but it doesnt work..

If you help me on this subject i will be happy…

How to append a div to another two div with the same ID using JavaScript

I’m trying to make a tic tac toe that every cell is another tic tac toe in html/js but I want to make the structure with js. But I can’t apply the function to create div in more than 1 div.

<script>
    function create_elements_from_html(n, html){
        const template = document.createElement("template")
        let htmlaux = ``
        for (a = 0; a < n; a += 1){
            htmlaux += html
        }

        template.innerHTML = htmlaux
        return template.content;
    }
    let big_board = create_elements_from_html(1, `<div id="big_board">big</div>`)
    document.body.appendChild(big_board)
    let small_board = create_elements_from_html(9, `<div id="small_board">small</div>`)
    document.getElementById("big_board").appendChild(small_board)
    let cell = create_elements_from_html(9, `<div id="cell">cell</div>`)
    document.getElementById("small_board").appendChild(cell)
</script>

I expected that this code return this but 9 times the small_board:

<div id="big_board"> big
    <div id="small_board"> small
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
        <div id = "cell"> cell</div>
    </div>
</div>

map through an object skipping some elements

Wondering how could I display a separator at any position in JSX? For instance, I have the following list which displays text when clicking on the item:

enter image description here

The code is the following:

<Accordion>
  {items.map((item, index) => (
    <AccordionItem key={item.id} item={item} index={index} />
  ))}
</Accordion>

Having an object like this declaring the content of the list:

const items = [
    { label: "One", content: "lorem ipsum for more, see https://one.com" },
    { label: "Two", content: "lorem ipsum for more, see https://two.com" },
    {
      label: "Three",
      content: "lorem ipsum for more, see https://three.com",
    },
  ];

Now, I’d like to add a separator after the label “Two” to get something like this:
enter image description here

If we try the following way, I get active the element in index 0 and element in index2:

<Accordion>
  {items.slice(0, 2).map((item, index) => (
    <AccordionItem key={item.id} item={item} index={index} />
  ))}
  <hr />
  {items.slice(2).map((item, index) => (
    <AccordionItem key={item.id} item={item} index={index} />
  ))}
</Accordion>

Then, getting this incorrect result:
enter image description here

Why it is happening this? Because my Accordion object is the following:

import { useState, createContext } from "react";

export const AccordionContext = createContext({
  activeItemIndex: 0,
  setActiveItemIndex: () => 0,
});

export const Accordion = (props) => {
  const [activeItemIndex, setActiveItemIndex] = useState(0);

  return (
    <AccordionContext.Provider value={{ activeItemIndex, setActiveItemIndex }}>
      <ul>{props.children}</ul>
    </AccordionContext.Provider>
  );
};

At the beginning activeItemIndex is 0, so when applying slice(2) the first element is also index 0 (however the element is at index 2).

How could I get the line right after the second element in the list?

Thanks a lot

Is there a built-in function or simplified way to add a character n times to a string in JS? [duplicate]

I’m looking for a function which adds a character n times to a string, without using a custom function.

Is there a way to simplify this?

Example

const str = add_n_chars( ' ', 21 );

Current way

Currently I use the code below, but I have the feeling that there must be a more concise way for this.

let spaces = '';

for( let i = 0;  i < indent;  i++ )
    spaces += ' ';

Minio: Getting Number of Objects in a Bucket

I’m playing around with Minio using their JavaScript client and one of the features I was hoping to find is some API that gets the total number of objects in a bucket. The count is quite important for a frontend feature. Is there some implementation or workaround to get the total number of objects in a bucket from Minio using the JavaScript client?

Thanks!

Chartjs 4 – Fill area between stacked line and bar chart

I’m in the process of migrating over to chart.js 4.4.1 and in the prior version (2.9.4) I was able to fill the gap with a color as in the attached image.

2.9.4 sample img

In the newest version, I’m able to get close by using an opacity, but it’s not quite the same:
4.4.1 sample img

Any ideas on how to make that happen? I’m using the non-module JavaScript chartjs file.

See my test code below.

<canvas id="my-chart"></canvas>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
    <script>
        
        let labels = [];
        for (let year=2000; year <= 2010; year++) {
            labels.push(year);
        }

        const config = {
            data: {
                labels: labels,
                datasets: [
                    {
                        type: "bar",
                        label: "Product",
                        data: [1331320,2851137,5952127,6607851,11068289,12059067,12117998,11827962,16582836,20184478,23915606],
                        backgroundColor: "#bec38f",
                        order: 1
                    },
                    {
                        backgroundColor: "rgba(151,156,106,0.5)",// "#979c6a",
                        borderColor: "#826f68",
                        borderWidth: 3,
                        data: [1242306,2442693,5070218,5502960,8572948,7722718,6916448,7196356,10429229,12544283,15149568],
                        label: "Benchmark",
                        type: "line",
                        fill: true,
                        pointBackgroundColor: "#ffffff",
                        pointRadius: 5,
                        order: 0
                    }
                ]
            },
            options: {
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        stacked: true,
                        scaleLabel: {
                            display: false
                        },
                        ticks: {
                            callback: function(value, index, ticks) {
                                return ("$" + (value/1000000));
                            }
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        intersect: true,
                        callbacks: {
                            label: function(context) {
                                return ("$" + context.parsed.y.toString().replace(/B(?=(d{3})+(?!d))/g, ","));
                            }
                        }
                    }
                }
            }
        };

        new Chart(document.getElementById("my-chart"), config);

    </script>