Toggle the visibility of an element when a button is clicked

I am trying to perform an exercise where I toggle the visibility of an element by accessing its ID. I can get it to disappear when I click it. However I dont understand what is wrong with my code so that it doesn’t reappear when clicked. thanks

   <!DOCTYPE html>
<html lang="en">
<head>
    <style>
        #button {
            display: block;
        }
    </style>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="p1Text">Hello world</p>
    <button id="button">Buttonni</button>
    
    <script>
        let button = document.getElementById("button");

        document.getElementById("button").onclick = function() {
            if (button.style.display === "none") {
                button.style.display = "block";
            } else {
                button.style.display = "none";
            }
        };
    </script>
</body>
</html>

File upload with Remix.run: File object turns into a string in action

I am working on a Remix application where users can upload files via a form. I have a handler function for the form submission that takes the form data, including a file attachment, and posts it to my action.

The issue is, when I receive the file in the action, it seems to be received as a string rather than a File object or a Blob. When I check if the incoming object is an instance of a File using value instanceof File, it returns false.

Heres my handle submit:

 const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
        const requiredFields = [
            "projectName",
            "blockchain",
            "supply",
            "mintPrice",
            "mintDate",
            "twitterLink",
            "emailContact",
            "description",
            "teamSummary",
            "teamMembers",
            "references",
            "documents",
            "artwork",
            "marketing",
            "allowlist",
            "investment",
        ];
    const newErrors = {...initialErrors};
    let $form = event.currentTarget;
    let formData = new FormData($form);

    requiredFields.forEach(field => {
        if (!projectForm[field as keyof ProjectFormState]) {
            newErrors[field] = true;
        }
    });

    if (Object.values(newErrors).some(value => value)) {
        setErrors(newErrors);
        return;
    }

    console.log('projectForm', projectForm);

    Object.entries(projectForm).forEach(([key, value]) => {
        console.log('file type in submit', value instanceof File)
        if (value instanceof File) {
            console.log('file value', value)
            formData.append(key, value, value.name);
        } else {
            formData.set(key, value);
        }
    });

    submit(formData, {
        method: $form.getAttribute("method") as HTMLFormMethod ?? $form.method,
        action: $form.getAttribute("action") ?? $form.action,
    });
};

Here the file value log is called, however in my action:

export const action = async ({request}: ActionArgs) => {
const formData = await request.formData();
const project: ProjectFormFields = {} as ProjectFormFields;

await Promise.all(Array.from(formData.entries()).map(async ([key, value]) => {
    console.log(key, value); // Log the value of 'value'
    console.log(value instanceof File); // Check whether 'value' is a File instance
    if (value instanceof File) {
        const arrayBuffer = await value.arrayBuffer();
        project[key] = Buffer.from(arrayBuffer);
    } else {
        project[key] = value;
    }
}));

console.log(project)

try {
    const response = await putProjectForm(project);
    const {status} = response;
    console.log('Form submission response', status);

    return redirect("/", {
        headers: {
            "Set-Cookie": `message=Your form was submitted successfully; Path=/;`,
        },
    });

} catch(error) {
    console.error('There was an error with the form submission', error);
}

return null;

}

The console.log(value instanceof File); returns false. Im not sure if its how im appending the file onto the formdata. But any help would be massive! Thanks!

Is there a way to prevent a Chrome extension from overwhelming the browser with tabs?

I was trying to write my browser extension. The idea was simple: re-open some urls in the new incognito tab.

But accidentally, I wrote a fork bomb ¯_(ツ)_/¯ that opens dozens of tabs every second.

So Chrome become unusable, and I’m unable to suspend my extension.

First of all, I tried to open Chrome without any extension launched – obviously, there were no extension to delete.

Then, I figured out that my extension isn’t located in the /Extensions/ folder.

And after that I tried to write a simple PowerShell script that will launch the Chrome and kill each process with a different pid.

$chromeProcess = Start-Process -FilePath "C:Program FilesGoogleChromeApplicationchrome.exe" -PassThru

for (;;) {
    $chromeProcesses = Get-Process -Name "chrome.exe"
    foreach ($process in $chromeProcesses) {
        if ($process.Id -ne $chromeProcess.Id) {
            Stop-Process $process.id
            Write-Host $process.Name + " " + $process.id
        }
    }
}

But, unfortunatelly, it doesn’t do so much – JavaScript is faster 🙂

And I really don’t want to reinstall Chrome.

How can I fix the issue with my second header not appearing during slide-in of the main header?

I have a test html file with 2 headers. The first header is supposed to slide-out out of the page when I scroll past a certain amount of pixels and it does, but at that same time the second header is supposed to appear under the main header and slide at the same time as the main header. The second one is supposed to stop at the old place of my main header. But unfortunately is doesn’t even appear. Nor does my js file make it slide.

window.addEventListener("DOMContentLoaded", function() {

  var mainHeader = document.getElementById("myHeader");

  // Add the scroll event listener
window.addEventListener("scroll", function() {
  var oldHeader = document.getElementById('myHeader');
  var newHeader = document.getElementById('newHeader');
  
  if (window.pageYOffset > 0) {
    oldHeader.style.borderBottom = "1px solid lightgrey"; 
  } else {
    oldHeader.style.borderBottom = "none";
  }
  
  if (window.pageYOffset >= 100) {
    oldHeader.style.transform = "translateY(-100%)";
    newHeader.style.transform = "translateY(0%)";
  } else {
    oldHeader.style.transform = "translateY(0%)";
    newHeader.style.transform = "translateY(-100%)";
  }
});

  var navItems = document.querySelectorAll(".nav-item");

  navItems.forEach(function(navItem, index) {
    var submenu = navItem.querySelector(".submenu");
    var submenuItems = submenu ? submenu.querySelectorAll("a") : [];

    var link = navItem.querySelector("a");
    if (
      link &&
      index !== 2 &&
      submenuItems.length === 0
    ) {
      link.addEventListener("click", function(e) {
        e.stopPropagation();
        window.location.href = link.getAttribute("href");
      });
    }

    navItem.addEventListener("click", function(e) {
      var isActive = submenu && submenu.classList.contains("active");
      closeAllSubmenus();
      if (!isActive && index !== 2) {
        submenu && submenu.classList.add("active");
      }
      e.stopPropagation();
    });

    navItem.addEventListener("mouseover", function() {
      navItems.forEach(function(item) {
        if (item !== navItem) {
          item.querySelector("a").classList.add("hovered");
        }
      });
    });

    navItem.addEventListener("mouseout", function() {
      navItems.forEach(function(item) {
        if (item !== navItem) {
          item.querySelector("a").classList.remove("hovered");
        }
      });
    });

    submenuItems.forEach(function(item) {
      item.addEventListener("mouseover", function() {
        submenuItems.forEach(function(submenuItem) {
          if (submenuItem !== item) {
            submenuItem.classList.add("hovered");
          }
        });
      });

      item.addEventListener("mouseout", function() {
        submenuItems.forEach(function(submenuItem) {
          if (submenuItem !== item) {
            submenuItem.classList.remove("hovered");
          }
        });
      });
    });
  });

  function closeAllSubmenus() {
    var submenus = document.querySelectorAll(".submenu");
    submenus.forEach(function(submenu) {
      submenu.classList.remove("active");
    });
  }
});
* {
  box-sizing: border-box;
}

.sticky {
  position: fixed;
  top: 0;
  z-index: 100;
}

#headerContainer {
  position: sticky;
  top: 0;
  z-index: 100;
}

#myHeader,
#newHeader {
  position: sticky;
  top: 0;
  transition: transform 0.3s ease-in-out;
}

#headerPlaceholder {
  height: 73px; /* This should be the same height as your header */
  visibility: hidden; /* This ensures the div is invisible when not in use */
}

#myHeader.scrolled {
  border-bottom: solid 1px lightgrey;
}

#myHeader {
  position: fixed;
  top: 0px;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 73px;
  padding: 0 20px;
  border-bottom: solid 1px transparent;
  width: 100%;
  box-sizing: border-box;
  z-index: 100;
  transition: transform 0.3s ease-in-out, border-color 0.3s;
}

#myHeader.slide-out {
  transform: translateY(-100%);
  transition: transform 0.3s ease-in-out;
  border-color: transparent;
}

#newHeader {
  position: fixed;
  top: 73px;
  left: 0;
  display: none;
  justify-content: space-between;
  align-items: center;
  height: 73px;
  padding: 0 20px;
  border-bottom: solid 1px transparent;
  width: 100%;
  box-sizing: border-box;
  z-index: 99;
  opacity: 0;
  transition: top 0.3s ease-in-out, opacity 0.3s, border-color 0.3s;
  transform: translateY(-100%);
}

#newHeader.slide-in {
  top: 0;
  opacity: 1;
  border-color: lightgrey;
}

.visible {
  display: block;
}

.hidden {
  display: none;
}

.main {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1300px; /* adjust as needed */
  width: 100%;
}

@keyframes slideIn {
  0% {
    transform: translateY(-100%);
  }
  100% {
    transform: translateY(0);
  }
}

.border-bottom {
  border-bottom: 1px solid grey;
}

.logo {
  font-family: 'Open Sans', sans-serif;
  user-select: none;
}

nav {
  display: flex;
}

.nav-item {
  position: relative;
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  margin-right: 10px;
  display: inline-block;
  padding: 0 28px;
  cursor: pointer;
}

.nav-item a {
  color: black;
  text-decoration: none;
}

.submenu {
  display: none;
  position: absolute;
  top: calc(100% + 15px);
  left: 50%;
  transform: translateX(-50%);
  background-color: black;
  padding: 10px;
  border-radius: 24px;
  white-space: nowrap;
}

.submenu.active {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width: max-content;
}

.submenu a {
  display: block;
  padding: 5px 10px;
  color: white;
  font-weight: normal;
  transition: color 0.1s;
}

.submenu a:hover {
  font-weight: bold;
}

.button {
  display: flex;
  justify-content: space-between;
  width: calc(36px * 3 + 18px * 2);
}

.btn {
  width: 36px;
  height: 36px;
  background-color: green;
  margin-right: 10px;
}

.icon {
  width: 24px;
  height: 24px;
  background-color: white;
}
    <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=Open+Sans:wght@500&family=Poppins&family=Roboto:wght@300;400&display=swap" rel="stylesheet">
    <div id="headerContainer">
      <header id="myHeader">
        <div class="main">
          <div class="content">
            <div class="logo">
              <h2>Amin</h2>
            </div>
            <nav>
              <div class="nav-item"> About <div class="submenu">
                  <a href="#">Culture</a>
                  <a href="#">Community</a>
                  <a href="#">Milestones</a>
                </div>
              </div>
              <div class="nav-item"> Story <div class="submenu">
                  <a href="#">Archives</a>
                  <a href="#">History</a>
                </div>
              </div>
              <div class="nav-item">
                <a href="#">News</a>
              </div>
              <div class="nav-item"> Tech & Service <div class="submenu">
                  <a href="#">Tech</a>
                  <a href="#">Service</a>
                </div>
              </div>
              <div class="nav-item"> Responsibility <div class="submenu">
                  <a href="#">Promise</a>
                  <a href="#">ESG</a>
                  <a href="#">Social Impact</a>
                  <a href="#">Digital rights</a>
                  <a href="#">AI Ethics</a>
                </div>
              </div>
            </nav>
            <div class="buttons">
              <button class="btn">
                <div class="icon"></div>
              </button>
              <button class="btn">
                <div class="icon"></div>
              </button>
              <button class="btn">
                <div class="icon"></div>
              </button>
              <!-- Repeat above line for other buttons -->
            </div>
          </div>
        </div>
      </header>
      <header id="newHeader">
        <div class="main">
          <div class="content">
            <div class="logo"> <h2>Amin's Workspace</h2> </div>
          </div>
        </div>
      </header>
    </div>
    <h1 style="margin-top: 3000px">test</h1>
  

How do I fix the bug on DatePicker and TimePicker when details are not correctly recorded in MongoDB with MERN Stack?

Bug on DatePicker and TimePicker on MERN Stack

Hello!
I am facing an issue… When I book appointment, the details are sent. The information is showing up in mongoDB.

Everything is getting recorded but the timings and dates are not getting recorded correctly.

Whatever time & date I enter on the booking page of that doctor, the mongoDB only records time as 00:00 and date as current date.
Can you help me please??

The client code:

function BookAppoiment() {
    const [esteDisponibil, setEsteDisponibil] = useState(false);
    const navigate = useNavigate();
    const [date, setDate] = useState();
    const [ora, setOra] = useState();
    const params = useParams();
    const dispatch = useDispatch();
    const [doctor, setDoctor] = useState(null);
    const { user } = useSelector((state) => state.user);

    const getDoctorData = async () => {
        try {
            dispatch(showLoading());
            const response = await axios.post(
                '/api/doctor/get-doctor-info-by-id',
                { doctorId: params.doctorId },
                {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem('token')}`,
                    },
                }
            );
            dispatch(hideLoading());
            if (response.data.success) {
                setDoctor(response.data.data);
            }
        } catch (error) {
            console.log(error);
            dispatch(hideLoading());
        }
    };

    const checkAvailability = async () => {
        if (date && ora) {
            try {
                dispatch(showLoading());
                const response = await axios.post(
                    '/api/user/check-booking-availability',
                    {
                        doctorId: params.doctorId,
                        date: date,
                        ora: ora,
                    },
                    {
                        headers: {
                            Authorization: `Bearer ${localStorage.getItem('token')}`,
                        },
                    }
                );
                dispatch(hideLoading());
                if (response.data.success) {
                    toast.success(response.data.message);
                    setEsteDisponibil(true);
                } else {
                    toast.error(response.data.message);
                }
            } catch (error) {
                toast.error('Ceva nu a mers bine la verificarea disponibilității!');
                dispatch(hideLoading());
            }
        }
    };



    const bookNow = async () => {
        setEsteDisponibil(false);
        try {
            dispatch(showLoading());
            const response = await axios.post(
                '/api/user/book-appointment',
                {
                    doctorId: params.doctorId,
                    userId: user._id,
                    doctorInfo: doctor,
                    userInfo: user,
                    date: date,
                    ora: ora,
                },
                {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem('token')}`,
                    },
                }
            );
            dispatch(hideLoading());
            if (response.data.success) {
                toast.success(response.data.message);
                navigate('/appointments');
            }
        } catch (error) {
            toast.error('Ceva nu a mers bine la crearea programării!');
            dispatch(hideLoading());
        }
    };

    useEffect(() => {
        getDoctorData();
    }, []);

    return (
        <Layout>
            {doctor && (
                <div>
                    <h1 className="page-title">
                        {doctor.numeDoctor} {doctor.prenumeDoctor}
                    </h1>
                    <hr />
                    <Row gutter={20} className="mt-5" align="middle">
                        <Col span={12} sm={24} xs={24} lg={8}>
                            <h1 className="normal-text">
                                <b>Ore de lucru medic ales: </b>
                                {doctor.oreLucru[0]} - {doctor.oreLucru[1]}
                            </h1>
                            <div className="d-flex flex-column pt-2 mt-2">
                                {/* <DatePicker
                                    format="DD-MM-YYYY"
                                    onChange={(value) => {
                                        setDate(moment(value).format("DD-MM-YYYY"));
                                        setEsteDisponibil(false);
                                    }}
                                />

                                <TimePicker
                                    format="HH:mm"
                                    className="mt-3"
                                    onChange={(value) => {
                                        setEsteDisponibil(false);
                                        setOra(moment(value).format("HH:mm"));
                                    }}
                                /> */}
                                <DatePicker
                                    format="DD-MM-YYYY"
                                    onChange={(value) => {
                                        const formattedDate = value ? moment(value).format("DD-MM-YYYY") : null;
                                        setDate(formattedDate);
                                        setEsteDisponibil(false);
                                    }}
                                />

                                <TimePicker
                                    format="HH:mm"
                                    className="mt-3"
                                    onChange={(value) => {
                                        const formattedTime = value ? moment(value).format("HH:mm") : null;
                                        setOra(formattedTime);
                                        setEsteDisponibil(false);
                                    }}
                                />


                                {!esteDisponibil && (
                                    <Button
                                        className="butonPrincipal mt-3 full-width-buton"
                                        onClick={checkAvailability}
                                    >
                                        Verifică disponibilitatea
                                    </Button>
                                )}
                                {esteDisponibil && (
                                    <Button
                                        className="butonPrincipal mt-3 full-width-buton"
                                        onClick={bookNow}
                                    >
                                        Programează-te
                                    </Button>
                                )}
                            </div>
                        </Col>
                    </Row>
                </div>
            )}
        </Layout>
    );
}

export default BookAppoiment;

The server code:

router.post('/book-appointment', authMiddleware, async (req, res) => {
    try {
        req.body.status = "pending";
        req.body.date = moment(req.body.date, 'DD-MM-YYYY').format('YYYY-MM-DD');
        req.body.ora = moment(req.body.ora, 'HH:mm').format('HH:mm:ss');
        const newAppointment = new Appointment(req.body);
        await newAppointment.save();

        // Send notifications to the doctor based on their userId
        const user = await User.findOne({ _id: req.body.doctorInfo.userId });
        user.unseenNot.push({
            type: "new-appointment-request",
            message: `Pacientul ${req.body.userInfo.nume} ${req.body.userInfo.prenume} a făcut o nouă cerere de programare`,
            onClickPath: '/doctor/appointments',
        });
        await user.save();

        res.status(200).send({
            message: "Programare făcută cu succes!",
            success: true,
        });
    } catch (error) {
        console.log(error);
        res.status(500).send({
            message: "Eroare la crearea programarii",
            success: false,
            error,
        });
    }
});

router.post('/check-booking-availability', authMiddleware, async (req, res) => {
    try {
        const date = moment(req.body.date, 'DD-MM-YYYY').toISOString();

        const fromTime = moment(req.body.ora, "HH:mm").subtract(1, 'hours').toISOString();
        const toTime = moment(req.body.ora, "HH:mm").add(1, 'hours').toISOString();
        const doctorId = req.body.doctorId;

        const appointments = await Appointment.find({
            doctorId,
            date,
            ora: { $gte: fromTime, $lte: toTime },
        });

        if (appointments.length > 0) {
            return res.status(200).send({
                message: "Doctorul nu este disponibil pentru acea oră!",
                success: false,
            });
        } else {
            return res.status(200).send({
                message: "Doctorul este disponibil pentru acea oră!",
                success: true,
            });
        }
    } catch (error) {
        console.log(error);
        res.status(500).send({
            message: "Eroare la verificarea disponibilității programării!",
            success: false,
            error,
        });
    }
});

Expo AV: ‘if’ video has finished, go back to start

I am trying to create a function in Expo AV where ‘if’ the video has finished playing, it automatically returns to the start. The restart() function that I created does not allow this. Please excuse me as I am quite new to this! This is my code:

export default function App() {
  const video = React.useRef(null);
  const [status, setStatus] = React.useState({});

  const restart = () => {
    if (video.status.didJustFinish) {
      video.current.playFromPositionAsync(0);
    }
  };

  restart();

  return (
    <View style={styles.container}>
      <Video
        ref={video}
        style={styles.video}
        source={require("./assets/big_buck_bunny.mp4")}
        useNativeControls={false}
        volume={1.0}
        resizeMode={ResizeMode.CONTAIN}
        isLooping={false}
        onPlaybackStatusUpdate={status => setStatus(() => status)}
      />
      <View style={styles.buttons}>
        <TouchableOpacity onPress={() => status.isPlaying ? video.current.pauseAsync() : video.current.playAsync()}>
          {status.isPlaying ? (
            <>
              <AntDesign style={styles.icons} name="pause" size={50} color="white" />
            </>
          ) : (
            <>
              <AntDesign style={styles.icons} name="play" size={50} color="white" />
            </>
          )}
        </TouchableOpacity>
      </View>
    </View >
  );
}

shiny / rhandsontable / updating cells

In shiny, I have two tables displayed with rhandsontable, I have already implemented that whenever a cell value is changed the cell gets colored, however when switching between the tables all the changes disappear since naturally the table reloads everytime from the start, is it possible to somehow save the changed cell, so as long as you do not quit the session or do not press “reset” all the changes remain even if you switch between the tables?

(code based on the solution of the following thread: in shiny: rhandsontable / afterChange, change multiple cell backgrounds at once)

library(shiny)
library(rhandsontable)
library(tidyverse)

change_hook <- "function(el,x) {
  hot = this.hot;
  cellchngs = [];
  afterChange = function(changes, source) {
    $.each(changes, function (index, elem) {
      change = elem;                  /* gather the row, col, old, new values */
      if(change[2] !== change[3]) {   /* if old isn't the same as new */
        cellchg = ({rowind: change[0], colind: change[1]});
        cellchngs.push(cellchg);      /* add row and column indicies to array */
      }
    });
    $.each(cellchngs, function(ind, elem) { 
      td = hot.getCell(elem['rowind'], elem['colind']); /* get the html element */
      td.style.background = 'cyan';                     /* set background color */
    });
  }
  hot.addHook('afterChange', afterChange);  /* add event to table */
}"


ui <- div(actionButton(inputId = "reset_button",label = "Reset"), selectInput("data", "Choose data",choices=c("mtcars"=1, "iris"=2), selected=1)
          ,rHandsontableOutput(outputId="mtcars"))


server <- function(input, output, session) {
  
  
  reset <- reactiveVal(0)
  output$mtcars <- renderRHandsontable({
    r = reset()
    myvec <- c("mtcars", "iris")
    mydata <- eval(parse(text=myvec[as.numeric(input$data)]))
    rht = rhandsontable(mydata,reset=r,stretchH="all",height=300)
    reset(0)
    htmlwidgets::onRender(rht,change_hook)
  })
  
  observeEvent(input$reset_button,
               {
                 reset(1)
               })
}

shinyApp(ui, server)

Why couldn’t JS file detect a variable from .env file? (dotenv)

Problem:

The server cannot detect process.env.PORT from my .env file, saying PORT=5000, and I have dotenv installed. process.env.port returns undefined Is something wrong?


I have a very basic express server that runs fine:

const express = require('express');
const path = require('path');
const dotenv = require('dotenv')

const app = express();
const port = process.env.PORT || 8080;

// sendFile will go here
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});

app.listen(port);
console.log('Server started at http://localhost:' + port);
console.log(process.env.PORT) 

On server start:

Server started at http://localhost:8080
process.env.PORT = undefined

console.log(process.env.PORT) on the bottom of express script returned undefined


I have dotenv installed, proof:

$ npm ls dotenv       
eloquent-javascript@ /Users/dana/code/eloquent-javascript
└── [email protected]

My .env file has the following content:

PORT=5000

What is wrong with my setup?

I have express.js, .env and installed dotenv via npm.

Question: Why couldn’t express.js grab my variable via process.env.PORT from the .env file?

Could you find the issue with this neon cursor in javascript?

Please may i have a second view on this code. Something is wrong however I just cant seem to get this one right. Here is the link to the git post along with my code below
https://codepen.io/soju22/full/wvyBorP

I have tried importing three.js even though I know I dont need it. What I believe the issue to be is the javascript import of dependencies.

import { neonCursor } from 'threejs-toys'

neonCursor({
  el: document.getElementById('app'),
  shaderPoints: 16,
  curvePoints: 80,
  curveLerp: 0.5,
  radius1: 5,
  radius2: 30,
  velocityTreshold: 10,
  sleepRadiusX: 100,
  sleepRadiusY: 100,
  sleepTimeCoefX: 0.0025,
  sleepTimeCoefY: 0.0025
})
body, html, #app {
    margin: 0;
    width: 100%;
    height: 100%;
  }
  
  #app {
    overflow: hidden;
    touch-action: pan-up;
    color: #ffffff;
    font-family: 'Montserrat', sans-serif;
    text-align: center;
    text-shadow: 0 0 5px #ffffff, 0 0 20px #000, 0 0 30px #000;
  }
  
  #app h1 {
    --fontSize: 60px;
    --lineHeight: 80px;
    width: auto;
    height: calc(2 * var(--lineHeight));
    line-height: var(--lineHeight);
    margin: calc(50vh - var(--lineHeight)) auto 0;
    font-size: var(--fontSize);
    text-transform: uppercase;
  }
  
  #app a {
    margin-top: 10px;
    display: inline-block;
    text-decoration: none;
    color: #fff;
  }
  
  #app canvas {
    display: block;
    position: fixed;
    z-index: -1;
    top: 0;
  }
  
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>VD Capital</title>
        <link rel="stylesheet" href="test.css">
        <script src="https://kit.fontawesome.com/365cb50038.js" crossorigin="anonymous"></script>
        <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=Kumbh+Sans:wght@400;700&display=swap" rel="stylesheet">
        
    </head>
  <body>
    <div id="app">
        <div id="hero">
          <h1>NEON<br/>CURSOR</h1>
          <a target="_blank" href="https://github.com/klevron/threejs-toys">github/threejs-toys</a>
        </div>
    </div>
    <script type="module" src="test.js"></script>
  </body>
</html>

Fetch() will not work on url but will work on otherd [closed]

This code works generally with websites, but returns nothing on this one.

How can I get it to fetch data here?:

<script>
fetch('https://codeberg.org/alceawisteria/pages/src/branch/main/images/arthost')
  .then(response => response.text())
  .then(data => {
    const parser = new DOMParser();
    const htmlDoc = parser.parseFromString(data, 'text/html');
    const base = htmlDoc.createElement('base');
    base.href = 'https://codeberg.org/alceawisteria/pages/src/branch/main/images/arthost';
    htmlDoc.head.appendChild(base);
    const links = htmlDoc.querySelectorAll('a[href]');
    const linkList = document.createElement('ul');
    links.forEach(link => {
      const listItem = document.createElement('li');
      const anchor = document.createElement('a');
      anchor.href = link.href;
      anchor.target = '_blank'; // Set target to _blank
      anchor.textContent = link.href;
      listItem.appendChild(anchor);
      linkList.appendChild(listItem);
    });
    document.body.appendChild(linkList);
  })
  .catch(error => console.error(error));
</script>

Perhaps using XML text() ?

Or is this a CORS issue ?

Why are my JS element filters not working?

I want to create a filter where clicking on each box will remove any elements which don’t match that description. I have tried adding some code found on W3 but this isn’t working for me:
https://www.w3schools.com/howto/howto_js_filter_elements.asp

When I click on the boxes nothing is filtered off the page.

Image of project

```  <!--FILTER BUTTONS-->
    <div id="myBtnContainer">
      <button class="btn active" onclick="filterSelection('all')">
        Show all
      </button>
      <button class="btn" onclick="filterSelection('red')">Red</button>
      <button class="btn" onclick="filterSelection('yellow')">Yellow</button>
      <button class="btn" onclick="filterSelection('blue')">Blue</button>
      <button class="btn" onclick="filterSelection('green')">Green</button>
    </div>

    <!--THE TABLE-->
    <div id="myModal" class="modal">
        <div class="modal-content">
          <span class="close">&times;</span>
          <p id="modalText"></p>
        </div>
    </div>
    <div id="container"></div>

    <div class="periodic-table" class="filter-container">
        <div class="empty-space-1"></div>
        <div class="empty-space-2"></div>

        <button class="open-modal" class="filterDiv yellow" data-id="h1">
          <div class="periodic-element one">
            <div class="periodic-table-inner">
              <div class="title">h1</div>
              <div class="desc">Large Heading</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv yellow" data-id="style">
          <div class="periodic-element one">
            <div class="periodic-table-inner">
              <div class="title">Style</div>
              <div class="desc">Styling</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="anchor">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">A</div>
              <div class="desc">Anchor</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="comment">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">!-></div>
              <div class="desc">Comment</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="svg">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Svg</div>
              <div class="desc">Svg Image</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="ul">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">Ul</div>
              <div class="desc">Unordered List</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="br">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">Br</div>
              <div class="desc">Line Break</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv yellow" data-id="li">
          <div class="periodic-element one">
            <div class="periodic-table-inner">
              <div class="title">Li</div>
              <div class="desc">List</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv yellow" data-id="ol">
          <div class="periodic-element one">
            <div class="periodic-table-inner">
              <div class="title">Ol</div>
              <div class="desc">Ordered List</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="img">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Img</div>
              <div class="desc">Image</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="nav">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Nav</div>
              <div class="desc">Navigation</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="em">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Em</div>
              <div class="desc">Emphasized</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="div">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Div</div>
              <div class="desc">Groups Elements</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="link">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Link</div>
              <div class="desc">External Link</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="i">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">I</div>
              <div class="desc">Italic</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="u">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">U</div>
              <div class="desc">Underlined</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="b">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">B</div>
              <div class="desc">Bold text</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="col">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Col</div>
              <div class="desc">Column Properties</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="data">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Data</div>
              <div class="desc">M-R Data</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="body">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Body</div>
              <div class="desc">Main Content</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="dfn">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Dfn</div>
              <div class="desc">Defined term</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="title">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Title</div>
              <div class="desc">Tab Title</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv blue" data-id="meta">
          <div class="periodic-element two">
            <div class="periodic-table-inner">
              <div class="title">Meta</div>
              <div class="desc">Metadata</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv yellow data-id="abbr">
          <div class="periodic-element one">
            <div class="periodic-table-inner">
              <div class="title">Abbr</div>
              <div class="desc">Abbreviation</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="form">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">Form</div>
              <div class="desc">Form for User</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv red" data-id="h6">
          <div class="periodic-element four">
            <div class="periodic-table-inner">
              <div class="title">h6</div>
              <div class="desc">Small Heading</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="main">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Main</div>
              <div class="desc">Main Content</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv yellow" data-id="html">
          <div class="periodic-element one">
            <div class="periodic-table-inner">
              <div class="title">Html</div>
              <div class="desc">Root HTML</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="p">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">P</div>
              <div class="desc">Paragraph</div>
            </div>
          </div>
        </button>

        <button class="open-modal" class="filterDiv green" data-id="href">
          <div class="periodic-element three">
            <div class="periodic-table-inner">
              <div class="title">Href</div>
              <div class="desc">URL</div>
            </div>
          </div>
        </button>
    </div>
    <script type="text/javascript" src="javascript.js"></script>```


```/*FILTERS*/
.filter-container {
  overflow: hidden;
}

.filterDiv {
  float: left;
  background-color: #2196f3;
  color: #ffffff;
  width: 100px;
  line-height: 100px;
  text-align: center;
  margin: 2px;
  display: none; /* Hidden by default */
}

/* The "show" class is added to the filtered elements */
.show {
  display: block;
}

/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 12px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}

/* Add a light grey background on mouse-over */
.btn:hover {
  background-color: #ddd;
}

/* Add a dark background to the active button */
.btn.active {
  background-color: #666;
  color: white;
} ```


```// Filters
filterSelection("all");
function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("filterDiv");
  if (c == "all") c = "";
  // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
  }
}

// Show filtered elements
function w3AddClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {
      element.className += " " + arr2[i];
    }
  }
}

// Hide elements that are not selected
function w3RemoveClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
  }
  element.className = arr1.join(" ");
}

// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function () {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}```

File not included in request body using AJAX inside a Laravel Project

I have two modals in my Laravel project, one for creation and one for edit. Each of the modals supports file upload. The idea is, that a user can upload a file during the creation and that file can be replaces during the edit process. Worth mentioning that the creation part works as expected.

create-modal.blade.php

@hasVerified()
<div class="modal fade" id="create-case-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-auth" role="document">
        <div class="modal-content custom-modal-content">
            <div class="modal-header">
                <button type="button" class="btn-without-style custom-modal-icon-close ms-auto" data-bs-dismiss="modal"
                        aria-label="Close">
                    <img class="img-fluid" src="{{ asset('images/icons/cross-black.png') }}" alt="close">
                </button>
            </div>
            <div class="modal-body text-center p-0 m-0 mt-1">
                <div class="custom-modal-body">
                    {{--First page modal--}}
                    <div class="js-modal-case-1-page">
                        <h2 class="mb-0">@lang('Create Case')</h2>
                        <p class="main-text margin-top-15">@lang('Fill in the fields to create a case')</p>
                        <div class="wrapper-basic-modal margin-top-30 margin-bottom-30">
                            <form action="{{ route('case.store') }}" method="POST" id="form-case"
                                  class="case-form js-form-case js-create-case-form" enctype="multipart/form-data"
                                  accept-charset="utf-8">
                                @csrf
                                <input type="file" name="avatar" class="js-input-create-avatar-case"
                                       accept=".png, .jpg, .jpeg" hidden>
                                <div class="col-12 d-flex margin-top-30 z-index-1">
                                    <div>
                                        <img src="{{ asset('images/global/default.png') }}"
                                             class="case-upload-avatar js-img-create-case-avatar" alt="Avatar">
                                    </div>
                                    <div class="my-auto ms-4">
                                        <a href="javascript:void('Upload')"
                                           class="link-purple main-text-bold js-click-create-avatar-case">@lang('Cover Case')
                                        </a>
                                    </div>
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="name-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Name of the Business Case')</label>
                                    <br>
                                    <input id="name-case-modal" type="text" name="name" class="main-text"
                                           placeholder="@lang('Name of the Business Case')" autocomplete="name" value="">
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="desc-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Description')</label>
                                    <br>
                                    <textarea name="description" id="desc-case-modal"
                                              class="main-text" autocomplete="description"
                                              cols="15" rows="3" placeholder="@lang('Description')"></textarea>
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="problem-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Problem')</label>
                                    <br>
                                    <textarea name="problem" id="problem-case-modal"
                                              class="main-text" autocomplete="problem"
                                              cols="30" rows="3" placeholder="@lang('Problem')"></textarea>
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="requirement-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Requirements for the resolving')</label>
                                    <br>
                                    <textarea name="requirement" id="requirement-case-modal"
                                              class="main-text" autocomplete="requirement"
                                              cols="30" rows="3"
                                              placeholder="@lang('Requirements for the resolving')"></textarea>
                                    @errortag()
                                </div>

                                <div class="modal-input-group margin-top-25">
                                    <label for="delivery-date-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Delivery Date')</label>
                                    <br>
                                    <input type="date" name="delivery_date" class="main-text"
                                           id="delivery-date-modal" placeholder="@lang('Delivery Date')"
                                            min="{{ now() }}">
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="date-end-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Field')</label>
                                    <br>
                                    <select class="form-select form-select-custom main-text-bold"
                                            name="field_knowledge_id" aria-label="Desc for select">
                                        <option value="0" selected>@lang('Open this select menu')</option>
                                        @foreach($fields as $field)
                                            <option value="{{$field->id}}">{{$field->name}}</option>
                                        @endforeach
                                    </select>
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="modal-add-case-dropzone"
                                           class="main-text-bold margin-bottom-12">@lang('Files')</label>
                                    <div class="dropzone js-data-dropzone" id="modal-add-case-dropzone">
                                        <div class="dz-message" data-dz-message><span>@lang('Drop files here to upload')</span></div>
                                    </div>
                                </div>

                                <div class="margin-top-30 justify-content-between">
                                    <button type="button" data-form=".case-form"
                                            class="btn btn-orange btn-submit-modal mx-auto js-form-btn-save">@lang('Choose package')
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    {{--Second page modal--}}
                    <div class="js-modal-case-2-page margin-bottom-30" style="display: none">
                        <h2 class="mb-0">@lang('Publish case')</h2>
                        <p class="main-text margin-top-15 margin-bottom-60">@lang('Choose Package')</p>
                        <div class="wrapper-basic-modal margin-top-30 margin-bottom-60">
                            @if($productActionPublication)
                            <form action="{{ route('shop.case.checkout') }}" method="POST"
                                  class="case-form js-form-case js-form-case-price" enctype="multipart/form-data"
                                  accept-charset="utf-8">
                                @csrf
                                <div class="form-check text-start margin-top-25 mb-4">
                                    <input id="case" class="form-check-input disabled js-main-publish-case"
                                           type="checkbox" name="shop[0][price]"
                                           value="{{ $productActionPublication->product->st_price_id }}" checked>
                                    <label class="form-check-label" for="case">@lang('Publish case')</label>
                                    <span class="main-text-bold">
                                            {{ $productActionPublication->product->price }} €
                                        </span>
                                </div>
                                <p class="main-text-bold text-start mt-4 mb-3">@lang('Select how much of a solution you want to get for this')</p>
                                @foreach($packages as $key => $package)
                                    <div class="form-check text-start mb-3">
                                        <div class="mb-2">
                                            <input class="form-check-input" id="product{{ $key+1 }}" type="checkbox"
                                                   name="shop[{{ $key+1 }}][price]"
                                                   value="{{ $package->product->st_price_id }}">
                                            <label class="form-check-label main-text" for="product{{ $key+1 }}">
                                                {{ $package->product->name }} <span class="main-text-bold">{{ $package->product->price }} €</span>
                                            </label>
                                        </div>
                                        <label class="form-check-label main-text" for="product{{ $key+1 }}">
                                            <span class="main-text">
                                            ({{ $package->product->description }})
                                        </span>
                                        </label>
                                    </div>
                                @endforeach
                                @errortag()
                            </form>
                            @endif
                        </div>
                        <div class="margin-top-30 d-flex justify-content-between mb-4">
                            <div class="w-100">
                                <button type="button" data-form=".case-form"
                                        class="btn btn-grey btn-submit-modal js-form-btn-back">@lang('Back')
                                </button>
                            </div>
                            <div class="w-100 ms-4">
                                <button type="button" data-form=".case-form"
                                        class="btn btn-orange btn-submit-modal js-form-btn-publish-case">
                                <span class="spinner-border spinner-border-sm me-2 js-spinner" style="display: none;"
                                      role="status" aria-hidden="true"></span>
                                    @lang('Publish case')
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
        </div>
    </div>
</div>
@endhasVerified()

edit-modal.php

<div class="modal fade" id="edit-case-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-auth" role="document">
        <div class="modal-content custom-modal-content">
            <div class="modal-header">
                <button type="button" class="btn-without-style custom-modal-icon-close ms-auto" data-bs-dismiss="modal"
                        aria-label="Close">
                    <img class="img-fluid" src="{{ asset('images/icons/cross-black.png') }}" alt="close">
                </button>
            </div>
            <div class="modal-body text-center p-0 m-0 mt-1">
                <div class="custom-modal-body">
                    <div class="">
                        <h2 class="mb-0">@lang('Edit') @lang('Case')</h2>
                        <p class="main-text margin-top-15">@lang('Fill in the fields to Update a case')</p>
                        <div class="wrapper-basic-modal margin-top-30 margin-bottom-60">
                            <form action="{{ route('case.update', $case) }}" method="POST" id="edit-case-form"
                                  class="edit-case-form" enctype="multipart/form-data" accept-charset="utf-8">
                                @csrf
                                @method('PUT')
                                <input type="text" name="is_draft" value="{{ $case->is_draft }}" hidden>
                                <input type="filee" name="avatar" class="js-input-create-avatar-case"
                                       accept=".png, .jpg, .jpeg" hidden>
                                <div class="col-12 d-flex margin-top-30 z-index-1">
                                    <div>
                                        <img src="{{ $case->getFullUrlAvatar() }}"
                                             class="case-upload-avatar js-img-create-case-avatar" alt="Avatar">
                                    </div>
                                    <div class="my-auto ms-4">
                                        <a href="javascript:void('Upload')" class="link-purple main-text-bold js-click-create-avatar-case">@lang('Cover Case')
                                        </a>
                                    </div>
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="name-case-modal" class="main-text-bold margin-bottom-12">@lang('Name of the Business Case')</label>
                                    <br>
                                    <input id="name-case-modal" type="text" name="name" class="main-text js-case-name"
                                           placeholder="@lang('Name of the Business Case')" autocomplete="name" value="{{ $case->name }}">
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="desc-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Description')</label>
                                    <br>
                                    <textarea name="description" id="desc-case-modal"
                                              class="main-text js-case-desc" autocomplete="description"
                                              cols="30" rows="3" placeholder="@lang('Description')">{{ $case->description }}</textarea>
                                    @errortag()
                                </div>

                                <div class="modal-input-group margin-top-25">
                                    <label for="problem-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Problem')</label>
                                    <br>
                                    <textarea name="problem" id="problem-case-modal"
                                              class="main-text" autocomplete="problem"
                                              cols="30" rows="3" placeholder="@lang('Problem')">{{ $case->problem }}</textarea>
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="requirement-case-modal"
                                           class="main-text-bold margin-bottom-12">@lang('Requirements for the resolving')</label>
                                    <br>
                                    <textarea name="requirement" id="requirement-case-modal"
                                              class="main-text" autocomplete="requirement"
                                              cols="30" rows="3"
                                              placeholder="@lang('Requirements for the resolving')">{{ $case->problem }}</textarea>
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="delivery-date-modal" class="main-text-bold margin-bottom-12">@lang('Delivery Date')</label>
                                    <br>
                                    <input type="date" value="{{ $case->input_delivery_date }}" name="delivery_date" class="main-text" id="delivery-date-modal">
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="date-end-modal" class="main-text-bold margin-bottom-12">@lang('Field')</label>
                                    <br>
                                    <select class="form-select form-select-custom main-text-bold" name="field_knowledge_id" aria-label="Desc for select">
                                        <option value="0" selected>@lang('Open this select menu')</option>
                                        @foreach($fields as $field)
                                            <option {{ $field->id == $case->field_knowledge_id ? 'selected' : '' }} value="{{ $field->id }}">{{ $field->name }}</option>
                                        @endforeach
                                    </select>
                                    @errortag()
                                </div>
                                <div class="modal-input-group margin-top-25">
                                    <label for="modal-change-case-dropzone"
                                           class="main-text-bold margin-bottom-12">@lang('Files')</label>
                                    <div class="dropzone js-data-dropzone" id="modal-change-case-dropzone">
                                        <div class="dz-message" data-dz-message><span>@lang('Drop files here to upload')</span></div>
                                    </div>
                                </div>
                                <div class="margin-top-30">
                                    <button type="submit" data-form=".edit-case-form" class="btn btn-orange btn-submit-modal mx-auto js-form-btn-edit-case">@lang('Save')</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

The Javascript which includes handling the file upload:
case.js

    let files = [];
    let editFiles = [];

    // Initialize the Dropzone for the Add modal
    initDropzone($("#modal-add-case-dropzone"), files);

    // Initialize the Dropzone for the Edit modal
    initDropzone($("#modal-change-case-dropzone"), editFiles);

    function initDropzone(el, filesArray) {
        el.dropzone({
            url: "#",
            autoProcessQueue: false,
            uploadMultiple: false,
            parallelUploads: 1,
            maxFiles: 2,
            maxFilesize: 1024,
            addRemoveLinks: true,
            acceptedFiles: "application/pdf",
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },

            init: function () {
                let dropzoneInstance = this;

                if (window.existingFiles && window.existingFiles.length > 0) {
                    var existingFiles = window.existingFiles;

                    // TODO: Get requests sent wrongly
                    existingFiles.forEach(function (file) {
                        var mockFile = {
                            name: file.name,
                            size: file.size,
                            dataURL: file.url,
                        };

                        dropzoneInstance.displayExistingFile(
                            mockFile,
                            file.url
                        );

                        mockFile.previewElement.setAttribute("data-mock", "");
                    });
                }

                this.on("addedfile", function (file) {
                    var mockPreviews = document.querySelectorAll(
                        ".dz-preview[data-mock]"
                    );
                    mockPreviews.forEach(function (preview) {
                        preview.remove();
                    });

                    while (dropzoneInstance.files.length > 1) {
                        dropzoneInstance.removeFile(this.files[0]);
                    }

                    filesArray.push(file);

                    $(
                        "#modal-add-case-dropzone #modal-change-case-dropzone .dz-file-preview .dz-progress"
                    ).each(function () {
                        $(this).hide();
                    });
                });

                this.on("removedfile", function (file) {
                    let index = filesArray.findIndex(
                        (item) => item.name === file.name
                    );
                    if (index !== -1) {
                        filesArray.splice(index, 1);
                    }
                });
            },
        });
    }

    $(".js-form-btn-edit-case").on("click", function (e) {
        let dataForm = new FormData(editForm[0]);

        $(editFiles)
            .filter(function () {
                return this !== undefined;
            })
            .each(function (index) {
                dataForm.append(`file[]`, this);
            });

        $.ajax({
            type: "post",
            url: editForm.attr("action"),
            data: dataForm,
            cache: false,
            processData: false,
            contentType: false,
            success: function (response) {
                /*Checkout*/
                console.log(response);
            },
            error: function (error) {
                notification("error", JSON.parse(error.responseText).message);
            },
        });
    });

    $(".js-form-btn-publish-case").on("click", function (e) {
        // e.preventDefault();
        let checkedProducts = 0;
        $('input[type="checkbox"]:checked').each(function () {
            checkedProducts++;
        });
        if (checkedProducts >= 2) {
            /*Store case*/
            let dataForm = new FormData(form[0]);
            $(files)
                .filter(function () {
                    return this !== undefined;
                })
                .each(function (index) {
                    dataForm.append(`file[${index}]`, this);
                });
            preloader.addClass("preloader-modal");
            $(".js-spinner").show().parent().attr("disabled", true);
            $.ajax({
                type: "post",
                url: form.attr("action"),
                data: dataForm,
                processData: false,
                contentType: false,
                success: function (response) {
                    /*Checkout*/
                    $.ajax({
                        type: "post",
                        url: formPrice.attr("action"),
                        data: formPrice.serialize(),
                        success: function (response) {
                            // window.location.replace(response["url"]);
                            notification(
                                "success",
                                "Case created successfully"
                            );
                        },
                    });
                },
                error: function (error) {
                    notification(
                        "error",
                        JSON.parse(error.responseText).message
                    );
                },
            });
        } else {
            preloader.removeClass("preloader-modal");
            notification("error", "Please select at least 1 package");
        }
    });

The Laravel controller which handles the creation and update:
BusinessCaseController.php

<?php

...
class BusinessCaseController extends Controller
{

public $service;

public function __construct(BusinessCaseService $service)
{
    $this->service = $service;
}

...

/**
 * Store a newly created resource in storage.
 *
 * @param BusinessCaseRequest $request
 * @return Response
 */
public function store(BusinessCaseRequest $request): Response
{
    if ($case = $this->service->create($request->validated())) {
        Session::push('case', $case->id);
        return response(['message' =>  __('notification.successfully created', ['Name' => __('Case')]) ], 200);
    }
    return response(['message' =>  __('notification.failed created', ['Name' => __('Case')]) ], 422);
}

/**
 * Update the specified Case in storage.
 *
 * @param BusinessCaseRequest $request
 * @param BusinessCase $case
 * @return RedirectResponse
 * @throws SpatieMediaLibraryExceptionsMediaCannotBeUpdated
 */
public function update(BusinessCaseRequest $request, BusinessCase $case): RedirectResponse
{
    if ($this->service->update($request->validated(), $case)) {
        return redirect()->back()->with('notification', ['type' => 'success', 'message' => __('notification.successfully updated', ['Name' => __('Case')]) ]);
    }
    return redirect()->back()->with('notification', ['type' => 'error', 'message' => __('notification.failed updated', ['Name' => __('Case')])]);
}

}

The problem is that the file doesn’t reach the controller, so the problem should be on client side.
I’ve checked the validator and also tried to send the request itself to the service and log the result, but no luck, the file is not present in case of edit.
The creation process works as expected, so definitely I am missing something in case of the edit process.
I am not interested at the server side logic of file updating, I will handle that later, after I’ll have the necessary files there.

How can i get course name by map in javascript? I just want to know that how to get value from object inside another object by mapping

{
“_id”: “647388319578e5ca64aa7666”,
“firstName”: “Farhan”,
“lastName”: “Ahmed”,
“email”: “[email protected]”,
“password”: “password”,
“contact”: “03181119655”,
“course”: {
“_id”: “64722179e3f69ef2292103e1”,
“name”: “Web & Mobile App Development”,
“duration”: “6 Months”,
“fees”: 5000,
“shortName”: “W & M”,
“createdAt”: “2023-05-27T15:27:53.878Z”,
“updatedAt”: “2023-05-28T08:42:45.540Z”,
“__v”: 0
},
“createdAt”: “2023-05-28T16:58:25.546Z”,
“updatedAt”: “2023-05-28T16:58:25.546Z”,
“__v”: 0
}

  "course": {
    "_id": "64722179e3f69ef2292103e1",
    "name": "Web & Mobile App Development",
    "duration": "6 Months",
    "fees": 5000,
    "shortName": "W & M",
    "createdAt": "2023-05-27T15:27:53.878Z",
    "updatedAt": "2023-05-28T08:42:45.540Z",
    "__v": 0
  },