Getting violation Added non-passive event listener to a scroll-blocking ‘wheel’ event when trying to implement openlayers map and display coordinates

I am using OpenLayers map to display a map and coordinates of some ships at sea using Spring-Boot for backend, from where I am fetching ship coordinates and passing them to frontend using a REST API. But getting the following violation which stops rendering of the co-ordinates

Violation:
[Violation] Added non-passive event listener to a scroll-blocking ‘wheel’ event. Consider marking event handler as ‘passive’ to make the page more responsive. See https://www.chromestatus.com/feature/5745543795965952

Code to fetch data from backend:
let geoJson;

fetch('/ships') // replace with the actual API endpoint
    .then(response => response.json())
    .then(data => {
        // console.log(data)
        geoJson = {
            type: 'FeatureCollection',
            features: data.map(point => {
            return {
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [point.longitude, point.latitude]
                },
                properties: {
                    ShipName: point.ShipName,
                    MMSI: point.MMSI
                }
            }
        })
    };
    console.log(geoJson);
    })
    .catch(error => console.error(error));

Map Code:
window.onload = init;

function init(){
const map = new ol.Map({
    view: new ol.View({
        center: [0, 0],
        zoom: 2,
        projection: 'EPSG:4326'
    }),
    target: "map"
})

map.on('click', function(e){
    map.getView().setCenter(e.coordinate);
    map.getView().setZoom(6);
})

const openStreetMapStandard = new ol.layer.Tile({
    source: new ol.source.OSM({
        attributions: '<a href="https://www.openstreetmap.org/copyright">© OpenStreetMap</a>'
    }),
    visible: true,
    title: 'standard'
})

window.addEventListener('wheel', (event) => {
}, { passive: true });



const baseLayerGroup = new ol.layer.Group({
    layers: [
        openStreetMapStandard
    ]
})

const exLayer = new ol.layer.Vector({
    source: new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        features: new ol.format.GeoJSON().readFeatures(geoJson)
    }),
    visible: true,
    title: "metadata",
    style: new ol.style.Style({
        image: new ol.style.Icon({
            src: "./images/boat-with-containers_75931"
        })
    })
})

map.addLayer(baseLayerGroup);
// map.addLayer(exLayer)
}

`
Can anyone suggest how to implement that passive message handler or any other fix

Completely clueless with the error

RemoveEventListener is called only once and I don’t know why

When the add prompt button(addTodoBtnLm) is clicked an event listener is attached to the close button(closePromptBtn) inside the prompt. When the close button is clicked it removes the event listener as it should but if the add prompt button is clicked it doesn’t remove it.

const addTodoBtnLm = document.getElementById('todo-app-intro__add-btn');
const refreshQuoteBtn = document.getElementById('quote__btn');
const timsIntroBtns = {};

function checkActiveBtn(btnLm) {
  if (btnLm.getAttribute('aria-expanded') === 'false') {
    btnLm.classList.add('btn--active');
  } 
  else {  
    btnLm.classList.remove('btn--active');
  }
};

function showPrompt(hideTmId, promptLm, btnLm) {
  clearTimeout(hideTmId);
  promptLm.removeAttribute('hidden');
  btnLm.setAttribute('aria-expanded', true);
  setTimeout(() => {
    promptLm.classList.add('todo-app-prompt--active');
  }, 0);
}

function setHideTim(timeoutId, promptLm) {
  timsIntroBtns[timeoutId] = setTimeout(() => {
    promptLm.setAttribute('hidden', '');
  }, 1500);
}

function hidePrompt(promptLm, btnLm, closeBtnLm, wrappingFunction) {
  closeBtnLm.removeEventListener('click', wrappingFunction);
  btnLm.setAttribute('aria-expanded', false);
  promptLm.classList.remove('todo-app-prompt--active');
}

function addTodoPrompt() {
  const todoAppPromptLm = document.getElementById('todo-app-prompt');
  const closePromptBtn = document.getElementById('todo-app-prompt__cancel-btn');

  function wrappingFunction() {

/*I've tested it with the word wrapper, if the add button is clicked multiple
times and after the close button is clicked the word wrapper doesn't show 
once, but multiple times, as many times as the add prompt button has been
clicked.*/
    console.log('wrapper')

    checkActiveBtn(addTodoBtnLm);
    setHideTim('promptHideTmId2', todoAppPromptLm)
    hidePrompt(todoAppPromptLm, addTodoBtnLm, closePromptBtn, wrappingFunction);
  }

  checkActiveBtn(addTodoBtnLm);

  if (todoAppPromptLm.matches('.todo-app-prompt--active')) {
    setHideTim('promptHideTmId', todoAppPromptLm)

//this should remove the event listener but it doesn't.
    hidePrompt(todoAppPromptLm, addTodoBtnLm, closePromptBtn, wrappingFunction);
  } 
  else {
    showPrompt(timsIntroBtns.promptHideTmId, todoAppPromptLm, addTodoBtnLm);
    clearTimeout(timsIntroBtns.promptHideTmId2);
    closePromptBtn.addEventListener('click', wrappingFunction);
  }
}

addTodoBtnLm.addEventListener('click', () => {
  addTodoPrompt();
});

I’ve tried placing the removeEventListener inside the if statement, that detects if the prompt is open and closes it. It should remove the event listener too, but it doesn’t. Maybe is not the event listener and is another thing, the problem is that I want to remove the event listener when the prompt is closed because is not being used.

How to change delay of a certain image in slider?

I’m using Swiper.
How to increase delay for the first element only?
Slides are output dynamically like this:

{foreach $alldata as $item}
            {if !empty($item->url)}
                <a href="{$item->url}"
                   class="main-promo__slider-slide swiper-slide"
                   style="background-image: url('/storage/slider/{$item->img}')"
                   target="_blank">
                    {if !empty($item->mintext) || !empty($item->title)}
                        <div class="main-promo__slider-slide-content">
                            {if !empty($item->title)}
                                <p class="main-promo__slider-slide-title">{$item->title}</p>
                            {/if}
                            {if !empty($item->mintext)}
                                <p class="main-promo__slider-slide-text">{$item->mintext|truncate:200}</p>
                            {/if}
                        </div>
                    {/if}
                </a>
            {else}
            .........
        {/foreach}
    {/if}
</div>

According to docs you can do it like this:

<div class="swiper-slide" data-swiper-autoplay="2000">

But how to implement it in my case?

Virtual Backgrounds Not Rendering Properly: Seeking Guidance on WebRTC Implementation

I am working on integrating virtual background support into a video calling application using the RobustVideoMatting library (GitHub Repository). The segmentation of the foreground is successful, but I am facing a challenge with the background rendering during WebRTC streaming, i am not able to apply background image to the segmented video.

Methods Tried:

Method 1 – CSS Styling:

const bg = `url('${this.bg}') center center / cover`;
this.canvas.style.background = bg;

Method 2 – HTMLImageElement:

const backgroundImage = new Image();
backgroundImage.src = "https://d..........................jpg";
backgroundImage.onload = () => {
    canvasRef.current.getContext("2d").drawImage(backgroundImage, 0, 0, 640, 480);
}

Request for Assistance:

I am seeking guidance on resolving this issue. If anyone has experience with virtual backgrounds and WebRTC, or if there are specific considerations when using the RobustVideoMatting library, your insights would be greatly appreciated.

GitHub Repository: PeterL1n/RobustVideoMatting

CodePen Link CodePen Reference

Need to apply the background image or video to the segmented video frames.

chartjs-4.4.2 and chartjs-plugin-annotation in local library

I’m new to chartjs so please bear with me 🙂
On debian 12 I’ve npm installed chart.js and chartjs-plugin-annotation

Using the above mentioned libraries from local library no rectangle is visible.

Using

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>

the desired rectangle is visible.

Can anyone provide a working example using local librariers and chartjs-4.4.2?

How can i fetch the publication date of a Youtube Video using javascript?

I have been developping a plugin on Firefox which fetches date from the html source code of Youtube Videos. I am trying to find a way to fetch the publication date of the video, however my function is not working. Can you help me find what’s wrong, and help me come up with a fix ? Also, I cannot use the Youtube API or any exterior information source other thant the Youtube page itself.

My code works by looking through the html and then when it find “datePublished”, it copies the content.

Creating carousel using LinkedIn APIs

I have been trying to use the LinkedIn APIs to post a carousel.
I looked into the documentation but the only mention of Carousel is in Carousel Ads.

Upon some research, I could see that the PDF is being converted to images and then used as the carousel.

Some applications like Taplio, and Supergrow have the feature to post Carousels.

I tried using “/v2/ugcPosts/” API to post images by setting “shareMediaCategory”: “CAROUSEL” (based on the documentation here).

But I got the following error:

{
  "message": "com.linkedin.content.common.ResponseException: Carousel post must be a sponsored post: {lifecycleState=PUBLISHED, specificContent={com.linkedin.ugc.ShareContent={shareCommentary={text=Testing}, shareMediaCategory=CAROUSEL, media=[{thumbnails=[], status=READY, media=urn:li:digitalmediaAsset:ASSET_URN}, {thumbnails=[], status=READY, media=urn:li:digitalmediaAsset:ASSET_URN}]}}, visibility={com.linkedin.ugc.MemberNetworkVisibility=PUBLIC}, author=urn:li:member:URN, clientApplication=urn:li:developerApplication:ID, ugcOrigin=API, id=urn:li:share:ID, distribution={feedDistribution=MAIN_FEED}}.",
  "status": 403
}

Here is the payload:

{
  "author": "urn:li:person:USER_URN",
  "lifecycleState": "PUBLISHED",
  "specificContent": {
    "com.linkedin.ugc.ShareContent": {
      "shareCommentary": {
        "text": "Testing"
      },
      "shareMediaCategory": "CAROUSEL",
      "media": [
        {
        "status": "READY",
        "media": "urn:li:digitalmediaAsset:ASSET_URN"
      },
      {
        "status": "READY",
        "media": "urn:li:digitalmediaAsset:ASSET_URN"
      }
        ]
    }
  },
  "visibility": {
    "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
  }
}

Any help would be really appreciated.

Regards.

I was trying to post a carousel on LinkedIn using “Share on LinkedIn” APIs

Base64 pdf is not loading in iframe popup in blazor

If you’re encountering issues with loading large PDF files in a Blazor popup, it might be due to limitations in the size of data that can be handled efficiently, especially when using iframe or HTML encoded objects. Loading large files directly into the DOM can sometimes lead to performance issues or even outright failure.

Here is my javascript code block which is called from blazor code behind

Javascript code

function openPdf(base64PdfDoc) {
    "use strict";
    var left = window.screen.width;
    left = left > 0 ? left / 4 : 0;
    let pdfWindow = window.open("", 'winname', 'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=750, top = 0, left=' + left);
    pdfWindow.document.write(
        "<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
        encodeURI(base64PdfDoc) + "'></iframe>"
    );
}

Javascript called from Backend code

await JsRuntime.InvokeVoidAsync("openPdf", pdfContent);

Trying to bind in html as well but not working

                    <object width="100%" height="100%" data="data:application/pdf;base64,@base64pdfString" type="application/pdf" class="internal"
                    <embed src="data:application/pdf;base64,@base64courierlogpdfString" type="application/pdf" />
</object>

Alpine.js: Add form fields with x-model

I would like to try implement alpine.js framework into my existing native javascript function. I have an array of addresses (which contain street, postcode, etc) and it has an added function so that I can add multiple addresses for one customer. The code below is when I am using native javascript which works as desired:

<div>
    <form id="customerForm" method="post" action="{{ route('customers.store') }}">
        @csrf
        <div class="mb-4">
            ...
        </div>
        <div class="mb-4">
            ...
        </div>
        <div id="addressFields">
            <label>Address</label>
            <div class="address-fields">
                <div class="address-field mb-2">
                    <input type="text" name="addresses[0][street1]" placeholder="Street 1" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[0][street2]" placeholder="Street 2" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[0][postcode]" placeholder="Postcode" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[0][city]" placeholder="City" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[0][state]" placeholder="State" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[0][country]" placeholder="Country" />
                </div>
            </div>
        </div>
        <button type="button" id="addAddress">Add Address</button><br><br>
        <button type="submit">Create Customer</button>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        let addressIndex = 1;
        // Function to add address fields dynamically
        function addAddressFields() {
            const addressFields = document.getElementById('addressFields');
            const addressContainer = document.createElement('div');
            addressContainer.classList.add('address-fields');
            addressContainer.innerHTML = `
                <br/>
                <div>
                <label>Address ${addressIndex}</label>
                <button class ="removeAddress" id="removeAddress">Remove</button>
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${addressIndex}][street1]" placeholder="Street 1"/>
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${addressIndex}][street2]" placeholder="Street 2"/>
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${addressIndex}][postcode]" placeholder="Postcode"/>
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${addressIndex}][city]" placeholder="City"/>
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${addressIndex}][state]" placeholder="State"/>
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${addressIndex}][country]" placeholder="Country"/>
                </div>
            `;
            addressFields.appendChild(addressContainer);
            addressIndex++;
        }

        document.getElementById('addAddress').addEventListener('click', function() {
            addAddressFields();
        });

        document.addEventListener('click', function(event) {
            if (event.target.classList.contains('removeAddress')) {
                event.preventDefault();
                event.target.closest('.address-fields').remove();
                addressIndex--;
            }

        });
    });
</script>

Now, I already tried to use alpine.js based on my original code. There are some issue with it. Based on what I did, when I create customer, the addresses details only shows the latest addresses input. Meaning, for example, I fill up the addresses, then I want to add another one. So there are two addresses. When I create customer, it only display one addresses (which is the latest).

<div x-data="addresses: []">
    <form id="customerForm" method="post" action="{{ route('customers.store') }}">
        <div>
            ...
        </div>
        <div>
            ...
        </div>
        <template x-for="(address, index) in addresses" :key="index">
            <div>
                <label x-text="'Address ' + (index + 1)"></label>
                <div>
                    <input type="text" name="addresses[${index}][street1]" placeholder="Street 1"
                        x-model="address.street1" />
                </div>
                <div>
                    <input type="text" name="addresses[${index}][street2]" placeholder="Street 2"
                        x-model="address.street2" />
                </div>
                <div>
                    <input type="text" name="addresses[${index}][postcode]" placeholder="Postcode"
                        x-model="address.postcode" />
                </div>
                <div>
                    <input type="text" name="addresses[${index}][city]" placeholder="City" x-model="address.city" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${index}][state]" placeholder="State"
                        x-model="address.state" />
                </div>
                <div class="address-field mb-2">
                    <input type="text" name="addresses[${index}][country]" placeholder="Country"
                        x-model="address.country" />
                </div>
            </div>
        </template>
        <button type="button" @click="addresses.push({})">Add Address Alpinejs</button>
    </form>
</div>

I need help on how I can improve and fix my code. Thank you very much for your help and much appreciated.

This is when I add addresses

This is what has been displayed

How to restrict and only allow specific components as children in React and TypeScript using the Composition pattern

In my React (v17) TypeScript app I make use of the Composition pattern.

// types.ts
export type CardProps = {
  children: React.ReactElement | React.ReactElement[];
};

export type CardImageProps = {
  src: string;
  alt: string;
};

export type CardBodyProps = {
  children: ReactNode;
};

// CardImage.tsx
const CardImage = ({ src, alt }: CardImageProps) => {
  return (
    <img src={src} alt={alt} />
 );
};

// CardBody.tsx
const CardBody = ({ children }: CardBodyProps) => {
  return <div>{children}</div>;
};

// Card.tsx
const Card = ({ children }: CardProps) => {
  return (
    <div>
      {React.Children.map(children, (child) => {
        return child;
      })};
    </div>
  );
};

Card.Image = CardImage;
Card.Body = CardBody;

export default Card;

// Example feature
const ExampleFeature = () => (
  <Card>
    <Card.Image src="image/src" alt="The alt text" />
    <Card.Body>
       <h3>The title</h3>
       <p>Some body text</p>
    </Card.Body>
  </Card>
);

How can I restrict this <Card> feature on the defined child components, so inside <Card> you are only allowed to pass in (in this case), <Card.Body> and <Card.Image> and not something like a <p> tag or some other JSX syntax?

So e.g. you will see a TypeScript error when trying something like this and it will never render the <p> tag:

<Card>
  <p>Foo</p>
</Card>

How to make JavaScript Pair Game for matchig a different words

I’m trying to make a JavaScript Pair Game but with the poisons and antidotes format. So far, I have managed to do it by matching the same words, e.g. NALOXONE = NALOXONE. And I want to make e.g. OPIATE = NALOXONE and then it disappears.

The code is here:
https://github.com/andrzejhnatiuk/github.com-gramedyczna-gramedyczna.github.io/tree/main/index.html

Game page:
https://andrzejhnatiuk.github.io/github.com-gramedyczna-gramedyczna.github.io/index.html/

How can I do this?

How to use Arrays & Functions Correctly? In my code I have attempted to use two arrays to workout the score per section. But my code is to long

Context- CRM system, front-end form.

Requirement- Within a form users have to give a rating to a section based on user inputs, each rating has different weighting. The rating is stored in an option set field and the weighting for that rating is stored in another option set field. I previously have used JavaScript to calculate the average score of these rating fields through lots of variables.

I am now trying to use objects and methods to do this, although the way I have done this does not feel right.

Below is my code block, I would like to use an array to compare the value in my option set fields with my score and percentage array and perform the calculations.

// JavaScript source code
function CalculateAverageScore(executionContext) {
    var formContext = executionContext.getFormContext();
    var ScoreOptionA = formContext.getAttribute("dp_sectionamanagerrating").getValue();
    var PercentageOptionA = formContext.getAttribute("dp_sectionaquestionweighting").getValue();
    var ScoreOptionB = formContext.getAttribute("dp_sectionbmanagerrating");
    var PercentageOptionB = formContext.getAttribute("dp_sectionbquestionweighting");
    var ScoreOptionC = formContext.getAttribute("dp_sectioncmanagerrating");
    var PercentageOptionC = formContext.getAttribute("dp_sectioncquestionweighting");
    // Define the score array
    var score = [
        { "value": 778180000, "score": 1 },
        { "value": 778180001, "score": 2 },
        { "value": 778180002, "score": 3 },
        { "value": 778180003, "score": 4 },
        { "value": 778180004, "score": 5 }
    ];
    // Define the percentage array
    var percentage = [
        { "value": 778180000, "score": 0.10 },
        { "value": 778180001, "score": 0.20 },
        { "value": 778180002, "score": 0.30 },
        { "value": 778180003, "score": 0.40 },
        { "value": 778180004, "score": 0.50 }
    ]; 
    // Section A Calulations
    var SectionAScore = score.find(function (item) {
        return item.value === ScoreOptionA;
    });
    var SectionAPercentage = percentage.find(function (item) {
        return item.value === PercentageOptionA;
    });
    if ((SectionAScore) && (SectionAPercentage)) {
        var SectionAScore = SectionAScore.score;
        var SectionAPercentage = SectionAPercentage.score;
    }
    else {
        SectionAScore = 0;
        SectionAPercentage = 0;
    }
    // Section B Calculations 
    var SectionBScore = score.find(function (item) {
        return item.value === ScoreOptionB;
    });
    var SectionBPercentage = percentage.find(function (item) {
        return item.value === PercentageOptionB;
    });
    if ((SectionBScore) && (SectionBPercentage)) {
        var SectionBScore = SectionBScore.score;
        var SectionBPercentage = SectionBPercentage.score;
    }
    else {
        ScoreOptionB = 0;
        PercentageOptionB = 0;
    }
    // Section C Calculations 
    var SectionCScore = score.find(function (item) {
        return item.value === ScoreOptionC;
    });
    var SectionCPercentage = percentage.find(function (item) {
        return item.value === PercentageOptionC;
    });
    if ((SectionCScore) && (SectionCPercentage)) {
        var SectionBScore = SectionBScore.score;
        var SectionBPercentage = SectionBPercentage.score;
    }
    else {
        ScoreOptionC = 0;
        PercentageOptionC = 0;
    }
    // Caculations 
    Section1Score = SectionAScore * SectionAPercentage;
    Section2Score = SectionBScore * SectionBPercentage;
    Section3Score = SectionCScore * SectionCPercentage;
    AverageScore = Section1Score + Section2Score + Section3Score
    // Set Average Score Value
    formContext.getAttribute("dp_averagescoregeneraldecimal").setValue(averagescore);
}

For example ScoreOptionA = 778180000, so check that it matches a value in my array and based on the match set the score for ScoreOptionAValue to 1.Similarly for PercentageOptionA check it matches a value in my percentage array and based on the match set the score for my Percentage Option A.

Previously I had used standard variables and a function to achieve this, my code looked like this. I wanted to shorten my code through using an Array, but this has actually had the opposite effect.

// JavaScript source code
function CalculateAverageScore(executionContext) {
    var formContext = executionContext.getFormContext();
    var ScoreOptionA = formContext.getAttribute("dp_sectionamanagerrating");
    var PercentageOptionA = formContext.getAttribute("dp_sectionaquestionweighting");
    var ScoreOptionB = formContext.getAttribute("dp_sectionbmanagerrating");
    var PercentageOptionB = formContext.getAttribute("dp_sectionbquestionweighting");
    var ScoreOptionC = formContext.getAttribute("dp_sectioncmanagerrating");
    var PercentageOptionC = formContext.getAttribute("dp_sectioncquestionweighting");
    // Define Scoring & Percentages 
    var scoreMap = {
        778180000: 1,
        778180001: 2,
        778180002: 3,
        778180003: 4,
        778180004: 5
    };

    var percentageMap = {
        778180000: 0.10,
        778180001: 0.20,
        778180002: 0.30,
        778180003: 0.40,
        778180004: 0.50
    };
    var SectionAScore, SectionAPercentage, SectionBScore, SectionBPercentage, SectionCScore, SectionCPercentage;
    // Section A Score & Percentages 
    if (ScoreOptionA.getValue() != null && PercentageOptionA.getValue () != null) {
        var ScoreValueA = ScoreOptionA.getValue();
        var valuePercentageA = PercentageOptionA.getValue();
        SectionAScore = scoreMap[ScoreValueA];
        SectionAPercentage = percentageMap[valuePercentageA];
    }
    else {
        SectionAScore = 0;
        SectionAPercentage = 0;
    }
    //Section B Set Score & Percentages
    if (ScoreOptionB.getValue() != null && PercentageOptionB.getValue() != null) {
        var ScoreValueB = ScoreOptionB.getValue();
        var valuePercentageB = PercentageOptionB.getValue();
        SectionBScore = scoreMap[ScoreValueB];
        SectionBPercentage = percentageMap[valuePercentageB];
    }
    else {
        SectionBScore = 0;
        SectionBPercentage = 0;
    }
    // Section C Score & Percentages 
    if (ScoreOptionC.getValue() != null && PercentageOptionC.getValue() != null) {
        var ScoreValueC = ScoreOptionC.getValue();
        var valuePercentageC = PercentageOptionC.getValue();
        SectionCScore = scoreMap[ScoreValueC];
        SectionCPercentage = percentageMap[valuePercentageC];
    }
    else {
        SectionCScore = 0;
        SectionCPercentage = 0;
    }
    // Calculations
    var Section1Score = (SectionAScore * SectionAPercentage);
    var Section2Score = (SectionBScore * SectionBPercentage);
    var Section3Score = (SectionCScore * SectionCPercentage);
    var averagescore = (Section1Score + Section2Score + Section3Score);
    // Set Average Score Value
    formContext.getAttribute("dp_averagescoregeneraldecimal").setValue(averagescore);
}

ProblemWhenSendingDataToongodb [closed]

Hello I have to create a form to send data from a company to a database, my project is a react project and I use mongodb and express for the backend rating. My problem is that I can receive the company name, the phone number, the description and the company’s website but I can’t receive the schedules and rates. In my console when sending the form I send all the data including schedules and rates but impossible to receive them in my database. Thank you for your help!

App.jsx

import React, { useEffect, useState } from "react";
import axios from "axios";
import CompanyList from "./components/CompanyList";
import CompanyForm from "./components/CompanyForm";
import Horaire from "./components/Horaire";
import Home from "./components/Home";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Test from "./components/Test";
import Test2 from "./components/Test2";

function App() {
  const [entreprise, setEntreprise] = useState([]);
  const [nouvelleEntreprise, setNouvelleEntreprise] = useState({
    NomEntreprise: "",
    Description: "",
    Tel: "",
    Email: "",
    Tarif: "",
    SiteWeb: "",
    Horaire: Array.from({ length: 7 }, () => ({
      day: "",
      open: "",
      close: "",
      status: "open",
    })),
  });

  const chargerEntreprises = () => {
    axios
      .get("http://localhost:3001/entreprises")
      .then((entreprise) => {
        // console.log("Entreprises chargées avec succès:", entreprise.data);
        setEntreprise(entreprise.data);
      })
      .catch((err) =>
        console.log("Erreur lors du chargement des entreprises :", err)
      );
  };

  useEffect(() => {
    axios
      .get("http://localhost:3001/entreprises")
      .then((entreprise) => {
        // console.log(
        //   "Entreprises chargées avec succès lors du montage :",
        //   entreprise.data
        // );
        setEntreprise(entreprise.data);
      })
      .catch((err) =>
        console.log(
          "Erreur lors du chargement des entreprises lors du montage :",
          err
        )
      );
    chargerEntreprises();
  }, []);


 
  const ajouterEntreprise = async (e, data) => {
    e.preventDefault();
    console.log("Données envoyées depuis le formulaire :", data);

    // Format des horaires pour l'envoi au backend
    const formattedHours = data.Horaire.map(({ day, open, close, status }) => ({
      day,
      open,
      close,
      status,
    }));

    // Créez un nouvel objet avec les horaires correctement formatés
    const newData = {
      ...data,
      Horaire: formattedHours,
    };

    try {
      const response = await axios.post(
        "http://localhost:3001/entreprises",
        newData
      );
      console.log("Response from POST request:", response.data);

      // Réinitialiser le formulaire ou effectuer d'autres actions nécessaires
      setNouvelleEntreprise({
        NomEntreprise: "",
        Description: "",
        Tel: "",
        Email: "",
        Tarif: "",
        SiteWeb: "",
        Horaire: Array.from({ length: 7 }, () => ({
          day: "",
          open: "",
          close: "",
          status: "open",
        })),
      });

      // Mettez à jour les entreprises après l'ajout
      chargerEntreprises();
    } catch (error) {
      console.log("Erreur lors de la requĂŞte POST :", error.response.data);
    }
  };

  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="*" element={<Home />} />
          <Route path="/horaire" element={<Horaire />} />
          <Route
            path="/companyList"
            element={<CompanyList entreprises={entreprise} />}
          />
          <Route
            path="/companyForm"
            element={
              <CompanyForm
                ajouterEntreprise={(e, data) => ajouterEntreprise(e, data)}
                nouvelleEntreprise={nouvelleEntreprise}
                setNouvelleEntreprise={setNouvelleEntreprise}
              />
            }
          />
        </Routes>
      </BrowserRouter>
      <Test />
      {/* <Test2 /> */}
    </div>
  );
}

export default App;

//CompanyForm.jsx


import React, { useState } from "react";
import NavBar from "./NavBar";
import Horaire from "./Horaire";

function CompanyForm({
  ajouterEntreprise,
  nouvelleEntreprise,
  setNouvelleEntreprise,
}) {
  const [horaireSelected, setHoraireSelected] = useState(false);

  const handleAjouterEntreprise = (e) => {
    e.preventDefault();

    // Vérifiez si les champs obligatoires sont renseignés
    if (
      nouvelleEntreprise.Tel &&
      nouvelleEntreprise.Description &&
      nouvelleEntreprise.SiteWeb &&
      nouvelleEntreprise.Email &&
      nouvelleEntreprise.NomEntreprise &&
      nouvelleEntreprise.Tarif &&
      nouvelleEntreprise.Horaire
    ) {
      // Format des horaires pour l'envoi au backend
      const formattedHours = nouvelleEntreprise.Horaire.map(
        ({ day, open, close, status }) => ({
          day,
          open,
          close,
          status,
        })
      );
      console.log("Formatted Hours in CompanyForm:", formattedHours);
      // Créez un nouvel objet avec les horaires correctement formatés
      const newData = {
        ...nouvelleEntreprise,
        Horaire: formattedHours,
      };

      if (nouvelleEntreprise.Tarif) {
        newData.Tarif = nouvelleEntreprise.Tarif;
      }
      console.log("Nouvelles données à envoyer :", newData);

      // Appelez la fonction ajouterEntreprise avec les données du formulaire
      ajouterEntreprise(e, newData);
    } else {
      // Gérez le cas où les champs obligatoires ne sont pas remplis
      console.error("Veuillez remplir tous les champs obligatoires");
    }
  };

  return (
    <>
      <NavBar />
      <form onSubmit={handleAjouterEntreprise}>
        <div className="min-h-screen p-6 bg-gray-100 flex items-center justify-center company">
          <div className="container max-w-screen-lg mx-auto">
            <div>
              <div className="bg-white rounded shadow-lg p-4 px-4 md:p-8 mb-6">
                <div className="grid gap-4 gap-y-2 text-sm grid-cols-1 lg:grid-cols-3">
                  <div className="text-gray-600">
                    <p className="font-medium text-lg">
                      Ajouter une entreprise{" "}
                    </p>
                    <p>Merci</p>
                  </div>

                  <div className="lg:col-span-2">
                    <div className="grid gap-4 gap-y-2 text-sm grid-cols-1 md:grid-cols-5">
                      <div className="md:col-span-5">
                        <label>Nom de l'entreprise</label>
                        <input
                          type="text"
                          name="full_name"
                          id="full_name"
                          className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                          value={nouvelleEntreprise.NomEntreprise || ""}
                          onChange={(e) =>
                            setNouvelleEntreprise({
                              ...nouvelleEntreprise,
                              NomEntreprise: e.target.value,
                            })
                          }
                        />
                      </div>

                      <div className="md:col-span-5">
                        <label>Description</label>
                        <textarea
                          id="description"
                          name="description"
                          className="h-40 border mt-1 rounded px-4 w-full bg-gray-50 resize-none"
                          value={nouvelleEntreprise.Description || ""}
                          onChange={(e) =>
                            setNouvelleEntreprise({
                              ...nouvelleEntreprise,
                              Description: e.target.value,
                            })
                          }
                        ></textarea>
                      </div>

                      <div className="md:col-span-3">
                        <label>Email</label>
                        <input
                          type="email"
                          name="email"
                          id="email"
                          className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                          value={nouvelleEntreprise.Email || ""}
                          onChange={(e) =>
                            setNouvelleEntreprise({
                              ...nouvelleEntreprise,
                              Email: e.target.value,
                            })
                          }
                          placeholder="[email protected]"
                        />
                      </div>

                      <div className="md:col-span-2">
                        <label>Téléphone</label>
                        <input
                          type="tel"
                          name="telephone"
                          id="telephone"
                          className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                          pattern="[0-9]{10}"
                          value={nouvelleEntreprise.Tel || ""}
                          onChange={(e) =>
                            setNouvelleEntreprise({
                              ...nouvelleEntreprise,
                              Tel: e.target.value,
                            })
                          }
                        />
                      </div>
                      <div className="md:col-span-2">
                        <label>Site web</label>
                        <input
                          type="text"
                          name="siteweb"
                          id="siteweb"
                          className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                          value={nouvelleEntreprise.SiteWeb || ""}
                          placeholder="https://www.example.com"
                          onChange={(e) =>
                            setNouvelleEntreprise({
                              ...nouvelleEntreprise,
                              SiteWeb: e.target.value,
                            })
                          }
                        />
                      </div>
                      <div className="md:col-span-2">
                        <label>Tarifs</label>
                        <input
                          type="text"
                          name="Tarif"
                          id="Tarif"
                          className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                          value={nouvelleEntreprise.Tarif || ""}
                          onChange={(e) =>
                            setNouvelleEntreprise({
                              ...nouvelleEntreprise,
                              Tarif: e.target.value,
                            })
                          }
                        />
                      </div>
                      <div className="md:col-span-2">
                        <label>Horaire d'ouverture</label>
                        <div>
                          <Horaire
                            setHoraireSelected={setHoraireSelected}
                            updateBusinessHours={(hours) =>
                              setNouvelleEntreprise({
                                ...nouvelleEntreprise,
                                Horaire: hours,
                              })
                            }
                          />
                        </div>
                      </div>

                      <div className="md:col-span-5 text-right">
                        <div className="inline-flex items-end">
                          <button
                            // className={`bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded ${
                            //   horaireSelected
                            //     ? "cursor-pointer"
                            //     : "cursor-not-allowed"
                            // }`}
                            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                            onClick={handleAjouterEntreprise}
                          >
                            Ajouter Entreprise
                          </button>
                        </div>
                      </div>

                      {/* <div className="md:col-span-5">
                        <p className="font-medium text-lg">Horaires</p>
                        Vous pouvez remplacer 'daysOfWeek' par les jours de la semaine réels si nécessaire
                        {daysOfWeek.map((day) => (
                        {[
                          "Lundi",
                          "Mardi",
                          "Mercredi",
                          "Jeudi",
                          "Vendredi",
                          "Samedi",
                          "Dimanche",
                        ].map((day) => (
                          <div key={day}>
                            <label>{day}</label>
                            <div className="grid grid-cols-3 gap-4">
                              <input
                                type="text"
                                placeholder="Heure d'ouverture"
                                className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                                value={
                                  nouvelleEntreprise.Horaire.find(
                                    (h) => h.day === day
                                  )?.open || ""
                                }
                                onChange={(e) =>
                                  setNouvelleEntreprise((prev) => ({
                                    ...prev,
                                    Horaire: prev.Horaire.map((h) =>
                                      h.day === day
                                        ? { ...h, open: e.target.value }
                                        : h
                                    ),
                                  }))
                                }
                              />
                              <input
                                type="text"
                                placeholder="Heure de fermeture"
                                className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                                value={
                                  nouvelleEntreprise.Horaire.find(
                                    (h) => h.day === day
                                  )?.close || ""
                                }
                                onChange={(e) =>
                                  setNouvelleEntreprise((prev) => ({
                                    ...prev,
                                    Horaire: prev.Horaire.map((h) =>
                                      h.day === day
                                        ? { ...h, close: e.target.value }
                                        : h
                                    ),
                                  }))
                                }
                              />
                              <input
                                type="text"
                                placeholder="Statut"
                                className="h-10 border mt-1 rounded px-4 w-full bg-gray-50"
                                value={
                                  nouvelleEntreprise.Horaire.find(
                                    (h) => h.day === day
                                  )?.status || ""
                                }
                                onChange={(e) =>
                                  setNouvelleEntreprise((prev) => ({
                                    ...prev,
                                    Horaire: prev.Horaire.map((h) =>
                                      h.day === day
                                        ? { ...h, status: e.target.value }
                                        : h
                                    ),
                                  }))
                                }
                              />
                            </div>
                          </div>
                        ))}
                      </div> */}

                      <div className="md:col-span-5 text-right">
                        <div className="inline-flex items-end">
                          {/* <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                            Ajouter Entreprise{" "}
                          </button> */}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </>
  );
}

export default CompanyForm;




//Horaire.jsx
import React, { useState } from "react";
import Modal from "react-modal";

const Horaire = ({ setHoraireSelected, updateBusinessHours }) => {
  const [businessHours, setBusinessHours] = useState({
    Lundi: { status: "open", open: "", close: "" },
    Mardi: { status: "open", open: "", close: "" },
    Mercredi: { status: "open", open: "", close: "" },
    Jeudi: { status: "open", open: "", close: "" },
    Vendredi: { status: "open", open: "", close: "" },
    Samedi: { status: "open", open: "", close: "" },
    Dimanche: { status: "open", open: "", close: "" },
  });

  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [selected, setSelected] = useState(false);

  const handleChange = (day, field, value) => {
    setBusinessHours((prevBusinessHours) => ({
      ...prevBusinessHours,
      [day]: {
        ...prevBusinessHours[day],
        [field]: value,
      },
    }));
  };
  const handleSave = (e) => {
    e.preventDefault();

    // Format des horaires pour la mise Ă  jour dans CompanyForm
    const formattedHours = Object.entries(businessHours).map(
      ([day, hours]) => ({
        day,
        open: hours.open || "", 
        close: hours.close || "", 
        status: hours.status,
      })
    );
    console.log("Formatted Hours:", formattedHours);

    // Appelez la fonction updateBusinessHours avec les horaires formatés
    updateBusinessHours(formattedHours);
    closeModal();
  };

  const openModal = () => {
    setModalIsOpen(true);
  };

  const closeModal = () => {
    setModalIsOpen(false);
  };
  const handleSelection = (selectedHours) => {
    // Mettez à jour l'état local ou effectuez d'autres actions si nécessaire
    updateBusinessHours(selectedHours);
    // Mettez à jour l'état pour indiquer que des horaires ont été sélectionnés
    setHoraireSelected(true);
  };

  return (
    <>
      <button
        type="button"
        onClick={openModal}
        className={`h-10 border mt-1 rounded px-4 w-full ${
          selected ? "bg-green-100" : "bg-gray-50"
        }`}
      >
        {selected
          ? "Horaires sélectionnés"
          : "Ajouter des horaires d'ouvertures"}
      </button>
      <Modal
        isOpen={modalIsOpen}
        onRequestClose={closeModal}
        contentLabel="Business Hours Form"
      >
        <div className="max-w-2xl mx-auto mt-8 p-4 border border-gray-300 rounded">
          <div className="grid grid-cols-3 gap-4">
            {Object.entries(businessHours).map(([day, hours]) => (
              <div key={day} className="mb-4">
                <label
                  htmlFor={`${day}-status`}
                  className="block font-semibold mb-2 capitalize"
                >
                  {day}:
                </label>
                <select
                  id={`${day}-status`}
                  value={hours.status}
                  onChange={(e) => handleChange(day, "status", e.target.value)}
                  className="border border-gray-300 p-2 rounded focus:outline-none focus:border-blue-500"
                >
                  <option value="open">Ouvert</option>
                  <option value="closed">Fermé</option>
                </select>
                {hours.status === "open" && (
                  <div className="flex flex-col space-y-2 mt-2">
                    <div className="flex space-x-2">
                      <label htmlFor={`${day}-open`} className="self-center">
                        Ouverture:
                      </label>
                      <input
                        type="time"
                        id={`${day}-open`}
                        value={hours.open}
                        onChange={(e) =>
                          handleChange(day, "open", e.target.value)
                        }
                        className="border border-gray-300 p-2 rounded focus:outline-none focus:border-blue-500"
                      />
                    </div>
                    <div className="flex space-x-2">
                      <label htmlFor={`${day}-close`} className="self-center">
                        Fermeture:
                      </label>
                      <input
                        type="time"
                        id={`${day}-close`}
                        value={hours.close}
                        onChange={(e) =>
                          handleChange(day, "close", e.target.value)
                        }
                        className="border border-gray-300 p-2 rounded focus:outline-none focus:border-blue-500"
                      />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
          <button
            type="submit"
            onClick={handleSave}
            className="bg-blue-500 text-white py-2 px-4 rounded mt-4 hover:bg-blue-700 focus:outline-none focus:ring focus:border-blue-300"
          >
            Enregistrer
          </button>
        </div>
      </Modal>
    </>
  );
};

export default Horaire;



//Schéma Entreprise 

const mongoose = require("mongoose");
const validator = require("validator");

const entrepriseSchema = mongoose.Schema({
  NomEntreprise: {
    type: String,
    required: true,
  },
  // Logo: {
  //   type: Buffer,
  // },
  Tel: {
    type: String,
    required: true,
  },
  Email: {
    type: String,
    required: true,
    validate(v) {
      if (!validator.isEmail(v)) throw new Error("Email non valide");
    },
  },
  Tarif: {
    type: String,
    required: true,
  },
  // Photo: {
  //   type: Buffer,
  // },
  Description: {
    type: String,
    required: true,
  },
  Horaire: [
    {
      day: {
        type: String,
        // required: true,
      },
      open: {
        type: String,
        // required: true,
      },
      close: {
        type: String,
        // required: true,
      },
      // startTime: {
      //   type: String,
      //   required: true,
      // },
      // endTime: {
      //   type: String,
      //   required: true,
      // },
      status: {
        type: String,
        // required: true,
      },
    },
  ],
  SiteWeb: {
    type: String,
    required: true,
  },
});

const entrepriseModel = mongoose.model("Entreprise", entrepriseSchema);

entrepriseModel.pre("save", function (next) {
  const validationErrors = this.validateSync(); // Utilise validateSync pour obtenir les erreurs de validation synchrones
  if (validationErrors) {
    console.error("Erreurs de validation :", validationErrors.errors);
    next(new Error("Erreur de validation"));
  } else {
    next();
  }
});

module.exports = entrepriseModel;

//Express Database 


const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const entrepriseModel = require("./models/Entreprise.cjs");

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

mongoose.connect("mongodb://localhost:27017/Beez2Be", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.get("/entreprises", async (req, res) => {
  console.log("Requête get reçue pour /entreprises");
  try {
    const entreprises = await entrepriseModel.find();
    console.log("Entreprises récupérées avec succès:", entreprises);
    res.json(entreprises);
  } catch (err) {
    console.error("Erreur lors de la récupération des entreprises :", err);
    res.status(400).json("Error: " + err);
  }
});


app.post("/entreprises", async (req, res) => {
  console.log("Requête post reçue pour /entreprises");
  console.log("Données reçues :", req.body);

  const nouvelleEntreprise = new entrepriseModel(req.body);

  try {
    const savedEntreprise = await nouvelleEntreprise.save();
    console.log("Entreprise ajoutée avec succès :", savedEntreprise);

    // Envoyer la réponse avec les détails de l'entreprise ajoutée
    res.json(savedEntreprise);
  } catch (err) {
    console.error("Erreur lors de l'ajout de l'entreprise :", err);
    console.log("Erreurs de validation :", err.errors);
    res.status(400).json("Error: " + err);
  }
});

const PORT = 3001;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

Here is an example of what I send and what I receive in the database

This is the result when I send my form


{NomEntreprise: 'Test', Description: 'TestTestTestTestTest', Tel: '0909090909', Email: '[email protected]', Tarif: 'Test', …}
Description
: 
"TestTestTestTestTest"
Email
: 
"[email protected]"
Horaire
: 
(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
NomEntreprise
: 
"Test"
SiteWeb
: 
"Test.com"
Tarif
: 
"Test"
Tel
: 
"0909090909"
[[Prototype]]
: 
Object

And here's what I have in my database :

{
  "_id": {
    "$oid": "65e1a0fe40b7b4775ce93910"
  },
  "NomEntreprise": "Test",
  "Tel": "0909090909",
  "Description": "TestTestTestTestTest",
  "SiteWeb": "Test.com",
  "__v": 0
}

I just started react that’s why I’m struggling with a simple thing at first glance. I want to thank you for your help!

how could I create in js, to miss at the end of the quiz which answers I selected and which were right and wrong

how could I create in js, to miss at the end of the quiz which answers I selected and which were right and wrong. At the end, I have a button that says “Show Answer” and I want it to open a window where it can show me the answer I selected and the correct one. If it’s right it’s green, if it’s wrong it’s red.

questions.js

// creating an array and passing the number, questions, options, and answers
let questions = [
    {
    numb: 1,
    question: "What does HTML stand for?",
    answer: "Hyper Text Markup Language",
    options: [
      "Hyper Text Preprocessor",
      "Hyper Text Markup Language",
      "Hyper Text Multiple Language",
      "Hyper Tool Multi Language"
    ]
  },
    {
    numb: 2,
    question: "What does CSS stand for?",
    answer: "Cascading Style Sheet",
    options: [
      "Common Style Sheet",
      "Colorful Style Sheet",
      "Computer Style Sheet",
      "Cascading Style Sheet"
    ]
  },
    {
    numb: 3,
    question: "What does PHP stand for?",
    answer: "Hypertext Preprocessor",
    options: [
      "Hypertext Preprocessor",
      "Hypertext Programming",
      "Hypertext Preprogramming",
      "Hometext Preprocessor"
    ]
  },
    {
    numb: 4,
    question: "What does SQL stand for?",
    answer: "Structured Query Language",
    options: [
      "Stylish Question Language",
      "Stylesheet Query Language",
      "Statement Question Language",
      "Structured Query Language"
    ]
  },
    {
    numb: 5,
    question: "What does XML stand for?",
    answer: "eXtensible Markup Language",
    options: [
      "eXtensible Markup Language",
      "eXecutable Multiple Language",
      "eXTra Multi-Program Language",
      "eXamine Multiple Language"
    ]
  },
  // you can uncomment the below codes and make duplicate as more as you want to add question
  // but remember you need to give the numb value serialize like 1,2,3,5,6,7,8,9.....

  //   {
  //   numb: 6,
  //   question: "Your Question is Here",
  //   answer: "Correct answer of the question is here",
  //   options: [
  //     "Option 1",
  //     "option 2",
  //     "option 3",
  //     "option 4"
  //   ]
  // },
];

script.js

// creating an array and passing the number, questions, options, and answers
let questions = [
    {
    numb: 1,
    question: "What does HTML stand for?",
    answer: "Hyper Text Markup Language",
    options: [
      "Hyper Text Preprocessor",
      "Hyper Text Markup Language",
      "Hyper Text Multiple Language",
      "Hyper Tool Multi Language"
    ]
  },
    {
    numb: 2,
    question: "What does CSS stand for?",
    answer: "Cascading Style Sheet",
    options: [
      "Common Style Sheet",
      "Colorful Style Sheet",
      "Computer Style Sheet",
      "Cascading Style Sheet"
    ]
  },
    {
    numb: 3,
    question: "What does PHP stand for?",
    answer: "Hypertext Preprocessor",
    options: [
      "Hypertext Preprocessor",
      "Hypertext Programming",
      "Hypertext Preprogramming",
      "Hometext Preprocessor"
    ]
  },
    {
    numb: 4,
    question: "What does SQL stand for?",
    answer: "Structured Query Language",
    options: [
      "Stylish Question Language",
      "Stylesheet Query Language",
      "Statement Question Language",
      "Structured Query Language"
    ]
  },
    {
    numb: 5,
    question: "What does XML stand for?",
    answer: "eXtensible Markup Language",
    options: [
      "eXtensible Markup Language",
      "eXecutable Multiple Language",
      "eXTra Multi-Program Language",
      "eXamine Multiple Language"
    ]
  },
  // you can uncomment the below codes and make duplicate as more as you want to add question
  // but remember you need to give the numb value serialize like 1,2,3,5,6,7,8,9.....

  //   {
  //   numb: 6,
  //   question: "Your Question is Here",
  //   answer: "Correct answer of the question is here",
  //   options: [
  //     "Option 1",
  //     "option 2",
  //     "option 3",
  //     "option 4"
  //   ]
  // },
];

style.css

/* importing google fonts */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body{
    background: #007bff;
}

::selection{
    color: #fff;
    background: #007bff;
}

.start_btn,
.info_box,
.quiz_box,
.result_box{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 
                0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.info_box.activeInfo,
.quiz_box.activeQuiz,
.result_box.activeResult{
    opacity: 1;
    z-index: 5;
    pointer-events: auto;
    transform: translate(-50%, -50%) scale(1);
}

.start_btn button{
    font-size: 25px;
    font-weight: 500;
    color: #007bff;
    padding: 15px 30px;
    outline: none;
    border: none;
    border-radius: 5px;
    background: #fff;
    cursor: pointer;
}

.info_box{
    width: 540px;
    background: #fff;
    border-radius: 5px;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.info_box .info-title{
    height: 60px;
    width: 100%;
    border-bottom: 1px solid lightgrey;
    display: flex;
    align-items: center;
    padding: 0 30px;
    border-radius: 5px 5px 0 0;
    font-size: 20px;
    font-weight: 600;
}

.info_box .info-list{
    padding: 15px 30px;
}

.info_box .info-list .info{
    margin: 5px 0;
    font-size: 17px;
}

.info_box .info-list .info span{
    font-weight: 600;
    color: #007bff;
}
.info_box .buttons{
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 30px;
    border-top: 1px solid lightgrey;
}

.info_box .buttons button{
    margin: 0 5px;
    height: 40px;
    width: 100px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 1px solid #007bff;
    transition: all 0.3s ease;
}

.quiz_box{
    width: 550px;
    background: #fff;
    border-radius: 5px;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.quiz_box header{
    position: relative;
    z-index: 2;
    height: 70px;
    padding: 0 30px;
    background: #fff;
    border-radius: 5px 5px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0px 3px 5px 1px rgba(0,0,0,0.1);
}

.quiz_box header .title{
    font-size: 20px;
    font-weight: 600;
}

.quiz_box header .timer{
    color: #004085;
    background: #cce5ff;
    border: 1px solid #b8daff;
    height: 45px;
    padding: 0 8px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 145px;
}

.quiz_box header .timer .time_left_txt{
    font-weight: 400;
    font-size: 17px;
    user-select: none;
}

.quiz_box header .timer .timer_sec{
    font-size: 18px;
    font-weight: 500;
    height: 30px;
    width: 45px;
    color: #fff;
    border-radius: 5px;
    line-height: 30px;
    text-align: center;
    background: #343a40;
    border: 1px solid #343a40;
    user-select: none;
}

.quiz_box header .time_line{
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 3px;
    background: #007bff;
}

section{
    padding: 25px 30px 20px 30px;
    background: #fff;
}

section .que_text{
    font-size: 25px;
    font-weight: 600;
}

section .option_list{
    padding: 20px 0px;
    display: block;   
}

section .option_list .option{
    background: aliceblue;
    border: 1px solid #84c5fe;
    border-radius: 5px;
    padding: 8px 15px;
    font-size: 17px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

section .option_list .option:last-child{
    margin-bottom: 0px;
}

section .option_list .option:hover{
    color: #004085;
    background: #cce5ff;
    border: 1px solid #b8daff;
}

section .option_list .option.correct{
    color: #155724;
    background: #d4edda;
    border: 1px solid #c3e6cb;
}

section .option_list .option.incorrect{
    color: #721c24;
    background: #f8d7da;
    border: 1px solid #f5c6cb;
}

section .option_list .option.disabled{
    pointer-events: none;
}

section .option_list .option .icon{
    height: 26px;
    width: 26px;
    border: 2px solid transparent;
    border-radius: 50%;
    text-align: center;
    font-size: 13px;
    pointer-events: none;
    transition: all 0.3s ease;
    line-height: 24px;
}
.option_list .option .icon.tick{
    color: #23903c;
    border-color: #23903c;
    background: #d4edda;
}

.option_list .option .icon.cross{
    color: #a42834;
    background: #f8d7da;
    border-color: #a42834;
}

footer{
    height: 60px;
    padding: 0 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid lightgrey;
}

footer .total_que span{
    display: flex;
    user-select: none;
}

footer .total_que span p{
    font-weight: 500;
    padding: 0 5px;
}

footer .total_que span p:first-child{
    padding-left: 0px;
}

footer button{
    height: 40px;
    padding: 0 13px;
    font-size: 18px;
    font-weight: 400;
    cursor: pointer;
    border: none;
    outline: none;
    color: #fff;
    border-radius: 5px;
    background: #007bff;
    border: 1px solid #007bff;
    line-height: 10px;
    opacity: 0;
    pointer-events: none;
    transform: scale(0.95);
    transition: all 0.3s ease;
}

footer button:hover{
    background: #0263ca;
}

footer button.show{
    opacity: 1;
    pointer-events: auto;
    transform: scale(1);
}

.result_box{
    background: #fff;
    border-radius: 5px;
    display: flex;
    padding: 25px 30px;
    width: 450px;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.result_box .icon{
    font-size: 100px;
    color: #007bff;
    margin-bottom: 10px;
}

.result_box .complete_text{
    font-size: 20px;
    font-weight: 500;
}

.result_box .score_text span{
    display: flex;
    margin: 10px 0;
    font-size: 18px;
    font-weight: 500;
}

.result_box .score_text span p{
    padding: 0 4px;
    font-weight: 600;
}

.result_box .buttons{
    display: flex;
    margin: 20px 0;
}

.result_box .buttons button{
    margin: 0 10px;
    height: 45px;
    padding: 0 20px;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 1px solid #007bff;
    transition: all 0.3s ease;
}

.buttons button.restart{
    color: #fff;
    background: #007bff;
}

.buttons button.restart:hover{
    background: #0263ca;
}

.buttons button.quit{
    color: #007bff;
    background: #fff;
}

.buttons button.quit:hover{
    color: #fff;
    background: #007bff;
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Awesome Quiz App | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <!-- FontAweome CDN Link for Icons-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
    <!-- start Quiz button -->
    <div class="start_btn"><button>Start Quiz</button></div>

    <!-- Info Box -->
    <div class="info_box">
        <div class="info-title"><span>Some Rules of this Quiz</span></div>
        <div class="info-list">
            <div class="info">1. You will have only <span>15 seconds</span> per each question.</div>
            <div class="info">2. Once you select your answer, it can't be undone.</div>
            <div class="info">3. You can't select any option once time goes off.</div>
            <div class="info">4. You can't exit from the Quiz while you're playing.</div>
            <div class="info">5. You'll get points on the basis of your correct answers.</div>
        </div>
        <div class="buttons">
            <button class="quit">Exit Quiz</button>
            <button class="restart">Continue</button>
        </div>
    </div>

    <!-- Quiz Box -->
    <div class="quiz_box">
        <header>
            <div class="title">Awesome Quiz Application</div>
            <div class="timer">
                <div class="time_left_txt">Time Left</div>
                <div class="timer_sec">15</div>
            </div>
            <div class="time_line"></div>
        </header>
        <section>
            <div class="que_text">
                <!-- Here I've inserted question from JavaScript -->
            </div>
            <div class="option_list">
                <!-- Here I've inserted options from JavaScript -->
            </div>
        </section>

        <!-- footer of Quiz Box -->
        <footer>
            <div class="total_que">
                <!-- Here I've inserted Question Count Number from JavaScript -->
            </div>
            <button class="next_btn">Next Que</button>
        </footer>
    </div>

    <!-- Result Box -->
    <div class="result_box">
        <div class="icon">
            <i class="fas fa-crown"></i>
        </div>
        <div class="complete_text">You've completed the Quiz!</div>
        <div class="score_text">
            <!-- Here I've inserted Score Result from JavaScript -->
        </div>
        <div class="buttons">
            <button class="restart">Replay Quiz</button>
            <button class="quit">Quit Quiz</button>
        </div>
    </div>

    <!-- Inside this JavaScript file I've inserted Questions and Options only -->
    <script src="js/questions.js"></script>

    <!-- Inside this JavaScript file I've coded all Quiz Codes -->
    <script src="js/script.js"></script>

</body>
</html>

I create in js, to miss at the end of the quiz which answers I selected and which were right and wrong. At the end, I have a button that says “Show Answer” and I want it to open a window where it can show me the answer I selected and the correct one. If it’s right it’s green, if it’s wrong it’s red.