image slider with javascript with next previous button

The general appearance of the program is as follows:
enter image description here

the details
In this exercise, we complete a simple slider. You must add the previous and next button in this event. The next or previous image should be displayed when the next or previous button is clicked. You can use the functions defined in the initial project.

When the slider is on the last image and the next button is clicked, the first image should be displayed and also when the first image of the previous button is clicked, the last image should be displayed.

Note: When an image is displayed, its opacity must be 1 and the rest of the images must be 0.

Notes
You are only allowed to make changes to the main.js file.
html code :

const sliderImages = [
    "./images/image1.jpg",
    "./images/image2.jpg",
    "./images/image3.jpg",
    "./images/image4.jpg",
];
const sliderDom = document.getElementById("slider");

let currentImage = 0;

function renderImages() {
    sliderImages.forEach((image) => {
        sliderDom.innerHTML += "<img src='" + image + "' />";
    });
}

function clearImages() {
    const images = document.getElementsByTagName("img");
    for (let i = 0; i < images.length; i++) {
        images[i].style.opacity = 0;
    }
}

function showImage(image) {
    clearImages();
    document.getElementsByTagName("img")[image].style.opacity = 1;
}

function init() {
    renderImages();
    showImage(currentImage);
}

init();

let myBtn = document.querySelector("#prevButton");

myBtn.onclick = function() {
    const newImage = (currentImage + 1) % sliderImages.length;

    showImage(newImage);
}
let myBtn2 = document.querySelector("#nextButton");

myBtn2.onclick = function() {
    const newImage = (currentImage + 1) % sliderImages.length;
    showImage(newImage);


}
* {
  margin: 0;
  padding: 0;
}

button {
  padding: 8px;
}

.container {
  width: 500px;
  margin: 20px auto;
}

#slider {
  position: relative;
  height: 400px;
  margin-bottom: 20px;
}

#slider img {
  width: 500px;
  height: 400px;
  position: absolute;
  transition: all .5s;
}

.buttons {
  display: flex;
  justify-content: space-between;
}
<!DOCTYPE html>
<html lang="en">
<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">
  <link rel="stylesheet" href="style.css">
  <title>Slider</title>
</head>
<body>
  <div class="container">
    <div id="slider"></div>

    <div class="buttons">
      <button id="prevButton"><</button>
      <button id="nextButton">></button>
    </div>
  </div>
  
  <script src="main.js"></script>
</body>
</html>

a website that is blocked from being embedded in an iFrame. I need a legal workaround that allows me to post my store on my website

I need to add a website that is blocked from being embedded in an iframe. I need a legal workaround that allows me to post my store on my website. I’m not trying to hack anybody. Just want to safely and legally bypass this restriction. Thanks. 🙂
As it is not working kindly give me a solution or solve it and sent me the code will be appreciated thanks alot

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
  <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
  <META HTTP-EQUIV="Expires" CONTENT="-1">

  <html>

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>NextierAffiliate.com</title>

    <style type="text/css">
      <!-- html {
        height: 100% !important;
        margin-bottom: 0px;
      }
      
      td img {
        display: block;
      }
      
      body {
        margin-top: 0px;
        margin-left: 0px;
        margin-right: 0px;
      }
      
      #apDiv1 {
        POSITION: fixed;
        WIDTH: 292px;
        BOTTOM: -22px;
        DISPLAY: block;
        HEIGHT: 222px;
        VISIBILITY: visible;
        RIGHT: 145px;
        padding: 0px;
      }
      
      -->
    </style>

    <script language="javascript">
      function DoClose() { <!-- Close the Popup
        document.getElementById('apDiv1').style.visibility = "hidden";
        return false;
      }
    </SCRIPT>

    <script type="text/javascript">
      <!--
      function MM_reloadPage(init) { //reloads the window if Nav4 resized
        if (init == true) with(navigator) {
          if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
            document.MM_pgW = innerWidth;
            document.MM_pgH = innerHeight;
            onresize = MM_reloadPage;
          }
        }
        else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) location.reload();
      }
      MM_reloadPage(true);
      //-->
    </script>



  </head>

  <body>

    <iframe id="iframe" src="<%= Session(" goURL ") %>" style="margin:0; width:100%; height: 100%; border:none; " cellpadding="0"></iframe>

    <div id="apDiv1">

      <table width="200" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td><img src="<%= Session(" naPopupImage ") %>" width=4 00; height=1 93; alt="" usemap="#mfmLink" border="0" />
            <map name="mfmLink" id="mfmLink"><area shape="rect" coords="367,4,391,26" onmouseover=" this.style.cursor='pointer';" onclick= "DoClose()"  />
          <area shape="rect" coords="5,29,394,217" href="http://www.nextieraffiliate.com" target="_blank" />
      </map></td>
        </tr>
      </table>


  </body>

  </html>

How do i can close the selected Gif and once i close the Gif i can able to get other Gif?

am creating facebook post page for my project, and almost done, but am not getting how to close the selected gif and once i close the selected gif am not able to get other gif. If any knows please help.

import axios from "axios";
import { useState } from "react";
import { useEffect } from "react";
import "./componentsStyles/GifInText.css"
 
const GifInText = ({gifId}) => {

    const [post, setPost] = useState({});
    const [closeGif, setCloseGif] = useState(false)
     

    const fetchData = async () =>{
          await axios.get(`https://api.giphy.com/v1/gifs/${gifId}`,{
                params: { 
                    api_key: "Xoa3mXrWxKXw6lJscrKUTsbZsXLbGuGY",
                    gif_id: gifId
                }
            }).catch((error) =>{
                console.log("error at fetching gifID2", error);
              }).then(response => {
                setPost(response.data)
               
              });
            }
    useEffect(()=>{
        fetchData()
        }, [  ])

        

        return (
            <div className='gif-section'>   
            {post.data && (
                    <>
                    <div className='image-gifs'>
                     <i className="fas fa-times" onClick={()=>setCloseGif(!post)}></i>
                     <img className="live-gifs" src={post.data.images.fixed_height.url} alt="..."/>
                    </div>
                    </>
                )}
            </div> 
         )
}
export default GifInText;

Unexpected behaviour of javascript constant string [duplicate]

A constant variable defined with the primitive types like number, string cannot be changed. But I tried the following example in console and got unexpected behaviour.

const word = "example";
word[0] = 'a';
console.log(word) //prints "example"
console.log(word[0]) // prints "e"

As word variable is declared with the const and as the string is a primitive data type and as per the rule, we cannot change the constant string than how come the 2nd line in above code did not gave any error?

Set-Cookie not working properly in axios call

Explanation

here, I sent one get req to ABC.com/Users/Login using Axios after this I sent a post request to ABC.com/Users/Login with form data and Cookie.

but it does not work properly. It works properly in postmen

My Code

axios.get('ABC.com/Users/Login')
.then(async response => {

   console.log("call login page");
   let tokenKey = "__RequestVerificationToken";
   let tokenValue = "CfDJ8DF1Ubmz1lpEibYtvvnYRTVXaJ-HWILEtqE_A3bGmDrD-yyKyJPbYK7qrcS9AIzezPo5- 
    tOWmcXs6WgYThZP-5qo1o1XXpalkJDEPnBtnVa7EhaUYbY2XNcANuugyWgkIf3-O2-_f5h7mNu960qGIaM";
   const userName="XYZ";
   const pass="test@123";

   let form=new FormData();
   form.append('UserName', userName);
   form.append('Password', pass);
   form.append([tokenKey], tokenValue);

   headers={
        'Cookie':response.headers['set-cookie'];
   }

   await axios.post('ABC.com/Users/Login', form, 
   { headers: {...form.getHeaders(),...headers}})
   .then(async response => {
        console.log(`Login success in ${userName}`);
        console.log("response",response.data);
   })
   .catch(error => {
       console.log(error);
   });

}
.catch(error => {
console.log(error);
});

In the First Axios call, I got:-

Set-Cookie: .AspNetCore.Antiforgery.b02ILwhXMuw=CfDJ8DF1Ubmz1lpEibYtvvnYRTXz_0rOkGhY6OXEw3d3vsDNG81V4IaMPfVZm5Hk3_icgp_ToLDG9xKu2mcM1VtEOMnSCktfZwG7Dj9_549SUiKht6Yv33pozagGjseFsfXI74wBwu-mMJkzgwfPx3jS4OA; path=/; samesite=strict; httponly
Set-Cookie: ABC.Session=CfDJ8DF1Ubmz1lpEibYtvvnYRTViv4PoRc%2F7jhjXdtCo4m1GZbcMf60xe9sOva27QUGL0BvT2A2SQZaCmrXlj%2FVL9lTvower%2B1lF87MQVTwDQKAFoEODlnPfWEM6SsrqDa0tomlRynXOtyCROBltiwNI27vo3uo4Y8jEn834lZ4OHYG3; path=/; samesite=lax; httponly 

I Want to set cookie like this :-

Cookie: .AspNetCore.Antiforgery.b02ILwhXMuw=CfDJ8DF1Ubmz1lpEibYtvvnYRTXz_0rOkGhY6OXEw3d3vsDNG81V4IaMPfVZm5Hk3_icgp_ToLDG9xKu2mcM1VtEOMnSCktfZwG7Dj9_549SUiKht6Yv33pozagGjseFsfXI74wBwu-mMJkzgwfPx3jS4OA; ABC.Session=CfDJ8DF1Ubmz1lpEibYtvvnYRTViv4PoRc%2F7jhjXdtCo4m1GZbcMf60xe9sOva27QUGL0BvT2A2SQZaCmrXlj%2FVL9lTvower%2B1lF87MQVTwDQKAFoEODlnPfWEM6SsrqDa0tomlRynXOtyCROBltiwNI27vo3uo4Y8jEn834lZ4OHYG3

It works in postmen but not in Axios call. Even I used this also but its not working

let cook1 = response.headers['set-cookie'][0].replace(" path=/; samesite=strict; httponly", "");
let cook2 = response.headers['set-cookie'][1].replace("; path=/; samesite=lax; httponly", "");
let mainCookie=cook1 + " " + cook2
// mainCookie .AspNetCore.Antiforgery.b02ILwhXMuw=CfDJ8DF1Ubmz1lpEibYtvvnYRTUh3vyphSzebPn04M1GqaH8KdFgWLSBpj5a06HBUhoYBhWdiWJw7Yy5525ZcZ_WblCjF7AzWbhQl2dFbQTwOmzP3K7oa0CLirsSJYkhIG-fHGizaNo-3cf8YdSiECkGhMM; ABC.Session=CfDJ8DF1Ubmz1lpEibYtvvnYRTVEF0LnEGw51HveT2mRMrzmgbHiPWjs8UiPcGcqUpJBhTG1uBSE5NLG8tBwkW1XcJH3OxPcPPsaB30aaRREgroCkO1jw%2BJY6tavDFE0P9RTmk9%2Bf2CTVwaTWYRQgPGam1CWJfODoyCzHwiIdfl8ciJS
headers={
        'Cookie':mainCookie;
}

if else statment to display icons in react

I need to display icons according to data.id value, (the example icons display is in the comment code as well. can you suggest to me how to give an else if condition to display this icon according to the data.id value?

/* eslint-disable react/jsx-pascal-case */
import React, { Fragment, useState, useRef } from "react";
import { Col, Row } from "antd";
import { useNavigate } from "react-router-dom";
import { Menu, Transition } from "@headlessui/react";
import * as Icons from "../../assets/svg/mobile-icons";
import * as Icons2 from "../../assets/svg/icon";

import catData from  './CategoriesData'

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}

const catWomen = catData.catWomen.map ((data) => {

  return(
    { 
      id: data.id, 
      name: data.name, 
      icon: <Icons2.frock01 />,
      childs: data.childs
    }
  )
  }
)

const catMen = catData.catMen.map ((data) => {
  return(
    { 
      id: data.id, 
      name: data.name, 
      icon: <Icons2.frock01 />,
      childs: data.childs
    }
  )
  }
)

const catKids = catData.catKid.map ((data) => {
  return(
    { 
      id: data.id, 
      name: data.name, 
      icon: <Icons2.frock01 />,  
      childs: data.childs
    }
  )
  }
)

/*
const catWomen = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.frock01 />,
    childs: ["item2", "item8"],
  },
  {
    id: 3,
    name: "Shoes",
    icon: <Icons2.shoes06 />,
    childs: ["item3", "item7"],
  },
  { id: 4, name: "Bags", icon: <Icons2.purse01 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.bag05 />,
    childs: ["item5", "item2"],
  },
  { id: 6, name: "Beauty", icon: <Icons2.hat02 />, childs: ["item6", "item4"] },
];

const catMen = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.shirt1 />,
    childs: ["item2", "item8"],
  },
  { id: 3, name: "Shoes", icon: <Icons2.shoes1 />, childs: ["item3", "item7"] },
  { id: 4, name: "Bags", icon: <Icons2.bag05 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.purse02 />,
    childs: ["item5", "item2"],
  },
  { id: 6, name: "Grooming", icon: <Icons2.hat />, childs: ["item6", "item4"] },
];

const catKids = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.shirt1 />,
    childs: ["item2", "item8"],
  },
  {
    id: 3,
    name: "Shoes",
    icon: <Icons2.shoes05 />,
    childs: ["item3", "item7"],
  },
  { id: 4, name: "Bags", icon: <Icons2.bag05 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.bow />,
    childs: ["item5", "item2"],
  },
  {
    id: 6,
    name: "Grooming",
    icon: <Icons2.hat03 />,
    childs: ["item6", "item4"],
  },
];
*/
const Categories = () => {
  const navigate = useNavigate();

  function SubCategories(props) {
    return (
      <Transition
        enter="transition ease-out duration-100"
        enterFrom="transform opacity-0 scale-95"
        enterTo="transform opacity-100 scale-100"
        leave="transition ease-in duration-75"
        leaveFrom="transform opacity-100 scale-100"
        leaveTo="transform opacity-0 scale-95"
      >
        <Menu.Items className="origin-top absolute w-auto rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100 focus:outline-none">
          <div className="py-1 flex">{props.children}</div>
        </Menu.Items>
      </Transition>
    );
  }

  function DropDownItem(props) {
    const items = props.data.map((item) => (
      <Menu.Item key={item.id.toString()}>
        {({ active }) => (
          <div
            onMouseOver={() => setChild(item.id)}
            onClick={() => {
              item.id === 1
                ? navigate(`/allproducts?mainProductCategory=${props.parent}`)
                : navigate(
                    `/allproducts?mainProductCategory=${props.parent}&category=${item.name}`
                  );
            }}
            className={classNames(
              active ? "bg-gray-100 text-gray-900" : "text-gray-700",
              "grid grid-cols-8 block px-4 py-2 text-xs"
            )}
          >
            <div className="col-span-7">{item.name}</div>
            <div className="col-span-1">{item.icon}</div>
          </div>
        )}
      </Menu.Item>
    ));
    return (
      <>
        <div className="border-r border-gray-300 w-40 text-sm">{items}</div>
      </>
    );
  }

  const [child, setChild] = useState(1);

  function LoadChilds(props) {
    const childs = props.data[props.child - 1];
    const subItems = childs.childs.map((item) => (
      <Menu.Item key={item.toString()}>
        {({ active }) => (
          <div
            onClick={() => navigate(`/allproducts?mainProductCategory=${props.parent}&category=${childs.name}&subCategory=${item}`)}
            className={classNames(
              active ? "bg-gray-100 text-gray-900" : "text-gray-700",
              "block px-4 py-2 text-sm"
            )}
          >
            {item}
          </div>
        )}
      </Menu.Item>
    ));
    return <div className="w-56">{subItems}</div>;
  }

  const dropdownRef = useRef();

  return (
    <Row className="bg-white w-full" style={{ position: "fixed", border: 0 }}>
      <Col offset={2}>
        <div className="flex w-full gap-6 text-xs cursor-pointer mt-0.5">
          <Menu as="div">
            <div
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
              onClick={() => navigate(`/allproducts`)}
            >
              <p>Shop</p>
            </div>
          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>Women</p>
            </Menu.Button>
            <div ref={dropdownRef}>
              <SubCategories>
                <DropDownItem data={catWomen} parent="Women" />
                <LoadChilds child={child} data={catWomen} parent="Women" />
              </SubCategories>
            </div>
          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>Men</p>
            </Menu.Button>
            <div ref={dropdownRef}>
              <SubCategories>
                <DropDownItem data={catMen} parent="Men" />
                <LoadChilds child={child} data={catMen} parent="Men" />
              </SubCategories>
            </div>
          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>Kids</p>
            </Menu.Button>
            <div ref={dropdownRef}>
              <SubCategories>
                <DropDownItem data={catKids} parent="Kids" />
                <LoadChilds child={child} data={catKids} parent="Kids" />
              </SubCategories>
            </div>
          </Menu>

          <Menu as="div">
            <div
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >
              <p>About</p>
            </div>
          </Menu>
        </div>
      </Col>
    </Row>
  );
};

export default Categories;

Optimizing checklist for a lot of data

So I have a checklist for ~1500 items

here’s currently how I do it

  toggleOpenTimeSlot = (timeSlotId) => {
    if (this.isTimeSlotOpened(timeSlotId)) {
      this.setState({
        openedTimeSlots: this.state.openedTimeSlots.filter(
          (id) => id !== timeSlotId
        ),
      });
    } else {
      this.setState({
        openedTimeSlots: [...this.state.openedTimeSlots, timeSlotId],
      });
    }
  };

  isTimeSlotOpened = (timeSlotId) =>
    this.state.openedTimeSlots.includes(timeSlotId);

But this approach is very slow, every time I check a checkbox, it takes more than a second to rerender

I also tried something like this

 toggleOpenTimeSlot = (timeSlotId) => {
    if (this.isTimeSlotOpened(timeSlotId)) {
      this.setState((state) => {
        return {
          ...state,
          openedTimeSlots: {
            ...state.openedTimeSlots,
            [timeSlotId.toString()]: false,
          },
        };
      });
    } else {
      this.setState((state) => {
        const newOpenedTimeSlots = { ...state.openedTimeSlots };
        delete newOpenedTimeSlots[timeSlotId.toString()];

        return {
          ...state,
          openedTimeSlots: newOpenedTimeSlots,
        };
      });
    }
  };

  isTimeSlotOpened = (timeSlotId) =>
    this.state.openedTimeSlots[timeSlotId.toString()];

But it seems the performance gets worse after that

AgGrid access grid data in a CustomRowRenderer

I am using a AGGrid (actually via custom wrapper) and I have checkoboxes on each row.
Also, I have a bottom row with buttons. I want to enable/disable the buttons based on selected rows.

<AgGrid
                        id="dataListGrid"
                        containerProps={{style: {height: gridData.length * 30, minHeight: 180}}}
                        className="customGrid"
                        columnDefs={dataListColumns}
                        frameworkComponents={{checkboxColRenderer: checkboxColRenderer}}
                        gridDescription="List"
                        onGridReady={handleGridReady}
                        rowData={gridData}
                        enableBrowserTooltips={true}
                        pagination
                        paginationPageSize={100}
                        onCellClicked={onCellClicked}
                        onRowSelected={(params) => {
                              params.api.redrawRows({
                                rowNodes: [params.api.getPinnedBottomRow(0)],
                              });
                            }}
                        isFullWidthCell={(rowNode) => rowNode.rowPinned === 'bottom'}
                        fullWidthCellRenderer={CustomPinnedRowRenderer}
                        pinnedBottomRowData={[{}]}
                        {...props}
                    />   

My data looks like below;

let gridData = [{
            fmIdentifier: 'Test data 1',
            category: 'Test',
            comments: 'Test',
            fm: 'Test',
            gti: 'Test data',
            wins: 'Test',
            identifier: 'Test',
            status: 'Test data',
        }, {
            fmIdentifier: 'Test data 2',
            category: 'Test',
            comments: 'Test',
            fm: 'Test',
            gti: 'Test data',
            wins: 'Test',
            identifier: 'Test',
            status: 'Test data X',
            rowPinned: 'bottom'
        }]
        setDataListColumns(DataListColumns);
        setGridData(gridData);

Below is how my CustomPinnedRowRenderer looks;

class CustomPinnedRowRenderer {
  init(params) {
    this.eGui = document.createElement('div');
// QUESTION : I want to access the grid data here...param.api.data shows empty object {}
    const selectedNodes = params.api.getSelectedNodes();
    this.eGui.innerHTML = finalDOMStr; //finalDOMStr has HTML

  }

  getGui() {
    return this.eGui;
  }

  refresh() {
    return false;
  }
}

My question is inside the CustomPinnedRowRenderer (on row select), I want to check the param.api.data (so that I can accordingly render enabled/disabled buttons)

But param.api.data seems to be empty object for some reason ?

Javascript: Dynamic Image creation

I want to upload multiple images and display them on the webpage. Following is the code which I have done ->

let fileInput = document.getElementById("file-input");
let imageContainer = document.getElementById("images-space");
let numOfFiles = document.getElementById("num-of-files");

function preview(){
    imageContainer.innerHTML = "";
    numOfFiles.textContent = `${fileInput.files.length} Files Selected`;
    $("#images_2nd_div_heading").html('<p><b>You have Selected ' + 
   `${fileInput.files.length}` + ' Images.</b> (Click on the images to add Tags)</p>');
    var count = 1;
    var html2='';
    for(i of fileInput.files){
        let reader = new FileReader();
        let figure = document.createElement("figure");
        let figCap = document.createElement("figcaption");
        figCap.innerText = i.name;
        figure.appendChild(figCap);
        reader.onload=()=>{
            let img = document.createElement("img");
            img.setAttribute("src",reader.result);
            img.setAttribute("name","img"+count);
            figure.insertBefore(img,figCap);
        }
        imageContainer.appendChild(figure);
        reader.readAsDataURL(i);
    }

Now the images are loaded perfectly on the webpage. The only problem being that the img.setAttribute used for name is setting "name":img4 if I select 3 Images from the webpage.

I don’t know why it is happening .

Here is the HTML code ->

<div class="container1">
            <input type="file" id="file-input" name="file" accept="image/png, image/jpeg" onchange="preview()" oninput="this.className = ''" multiple>
            <label for="file-input">
              <i class="fa fa-upload choose_photo"></i> &nbsp; Choose Your Photos
            </label>
            <p id="num-of-files">
              No Files Chosen
            </p>
            <div id="images-space"></div>
          </div>
        </div>

Validate HTML forms using JavaScript

I challenged my self to create a simple html form using JavaScript yet I’m not sure if what I’m coding is right. I’m still a beginner in this language I hope someone could clarify me from my mistakes.

Input fields listed below and use JavaScript to validate them (use an internal declaration):

  1. Name: Any input will be accepted. Must be required.
  2. Birthday: Only 18 years and up only. Must be required.
  3. Email Address: Gmail are only accepted. Must be required.
  4. Email Address Confirmation: Email Address input must match. Must be required.
  5. Password: At least one capital letter, one number, and one special character must be included in the password. A total of eight characters are required.
  6. Password Confirmation: Password input must match. Must be required.

This is my code:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div class="container">
   <!-- Input Name -->
  <form action="submitted.html">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <br><br>

    <!-- Input Email -->
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" pattern="[a-z0-9._%+-][email protected]" title="Email must only be from Gmail" required>
    <br><br>

    <!-- Input Confirm Email -->
    <label for="ConfirmEmail">Confirm Email:</label>
    <input type="email" id="ConfirmEmail" name="ConfirmEmail" pattern="[a-z0-9._%+-][email protected]" title="Email must only be from Gmail" required>
    <br><br>
    
    <!-- Input Password -->
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" pattern="^(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,8}$" title="Password must have at least 1 Capital Letter, 1 Number, and 1 special character. Must have a total of 8 characters." required>
    <br><br>

    <!-- Input Confirm Password -->
    <label for="confirmPassword">Confirm Password:</label>
    <input type="password" id="confirmPassword" name="confirmPassword" pattern="^(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,8}$" title="Input must be the same with password." required>
    <br><br>

    <!-- Submit Button -->
    <input type="submit" value="Submit">
  </form>
</div>
                
<script>
var myEmail = document.getElementById("email");
var myConfirmEmail = document.getElementById("confirmEmail");
var myPassword = document.getElementById("password");
var myConfirmPassword = document.getElementById("confirmPassword");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var special = document.getElementById("special");
var length = document.getElementById("length");

myEmail.onkeyup = function(){
  // Email: Confirm
  function matchEmail(){
  if(myEmail != myConfirmEmail){   
    myConfirmEmail.classList.remove("invalid");
    myConfirmEmail.classList.add("valid");  
  }else{  
    myConfirmEmail.classList.remove("valid");
    myConfirmEmail.classList.add("invalid"); 
  }  
}  

}

// When the user starts to input there is a pop-up text or validation reminder
myPassword.onkeyup = function(){

  // Password: Validate capital letters
  var capital = /[A-Z]/g;
  if(myPassword.value.match(capital)){  
    capital.classList.remove("invalid");
    capital.classList.add("valid");
  }else{
    capital.classList.remove("valid");
    capital.classList.add("invalid");
  }

  // Password: Validate numbers
  var numbers = /[0-9]/g;
  if(myPassword.value.match(numbers)){  
    number.classList.remove("invalid");
    number.classList.add("valid");
  }else{
    number.classList.remove("valid");
    number.classList.add("invalid");
  }

  // Password: Validate special characters
  var special = /(?=.*[!@#$%^&*])/g;
  if(myPassword.value.match(special)){  
    special.classList.remove("invalid");
    special.classList.add("valid");
  }else{
    special.classList.remove("valid");
    special.classList.add("invalid");
  }

  // Password: Validate length exactly 8 characters
  if(myPassword.value.length == 8){
    length.classList.remove("invalid");
    length.classList.add("valid");
  }else{
    length.classList.remove("valid");
    length.classList.add("invalid");
  }

  // Password: Confirm
  function matchPassword(){  
  var pw1 = document.getElementById("myPassword");  
  var pw2 = document.getElementById("myConfirmPassword");  
  if(pw1 != pw2){   
    myConfirmPassword.classList.remove("invalid");
    myConfirmPassword.classList.add("valid");  
  }else{  
    myConfirmPassword.classList.remove("valid");
    myConfirmPassword.classList.add("invalid"); 
  }  
}   

}
</script>

</body>
</html>

I still haven’t finish it because I was stuck at the email address confirmation. Thank You!

Fetching data from firestore does not immediately shows data if I render the data using my searchList

I have this data where I fetch all of the products in Firestore:

const [products, setProducts] = useState([]);
  useEffect(() => {
    let isMounted = true;

    const getProducts = async () => {
      const querySnapshot = await getDocs(collection(db, "products"));
      const arr = [];
      querySnapshot.forEach((doc) => {
        arr.push({
          ...doc.data(),
          id: doc.id,
        });
      });
      if (isMounted) {
        setProducts(arr);
        setIsLoading(true);
      }
    };

    getProducts().catch((err) => {
      if (!isMounted) return;
      console.error("failed to fetch data", err);
    });

    return () => {
      isMounted = false;
    };
  }, []);

Example data of the product:

enter image description here

I also have this searcList so users can search any of the products, sizes, or categories. The problem here is that it does not immediately shows the data of the products once it is mounted. I have to first type in a specific product and it will display the specific item, and when I click x to clear the search field that is the time it will display all of the products. However, if I change the searcList.map to productList.map, it will immediately render the products

 const [searchList, setSearchList] = useState([]);
  const [searchKey, setSearchKey] = useState("");

  useEffect(() => {
    let x = [...products];
    x = x.filter((y) => {
      const key = searchKey.toLocaleLowerCase();
      const values = ["prodName", "size", "cat"];
      return values.some((val) => y[val].toLocaleLowerCase().includes(key));
    });
    setSearchList(x);
  }, [searchKey]);

  const handleClear = () => {
    console.log("clear");
    setSearchKey("");
  };

Displaying the searchList with a map:

{searchList.map((item, index) => (
          <List key={index}>
            <Paper>
              <ListItemText
                primary={item.prodName}
                secondary={
                  item.size + "(Size)" + "  -  " + item.cat + "(Category)"
                }
              />
                  <br />
                </div>
              ))}
            </Paper>
          </List>
        ))}

Browser XSLT, any way to get back to the original XML?

Say you have a source XML file with ?xml-stylesheet PI, so when you load it into a browser it will be transformed through the stylesheet. Let’s say the source XML file was transformed to HTML and is displayed. All good.

Now the HTML contains a script (javascript) element to do stuff. Is there any way, standard or secret, by which one could get back to the original source XML of the current document?

I did not find one, so I have the XSLT output the source into a head/script element with id=”source” and type=”text/xml”. But when I load that with

document.getElementById("source").firstChild 

I get text not the actual element. If I do DOMParser parseFromString, I get a namespace prefix undeclared error, because XSLT didn’t output the namespace prefixes that were already declared under this source node.

Perhaps there is some way with a different HTML element that it actually reads the content as DOM nodes, with all the namespaces, not as a mere text node.

I have tried to use other elements than script, for example, there is a tag called <xml> in HTML, which you can use to embed XML. And when I use this, the

document.getElementById("source").firstChild 

actually gets me an element, not just a text node.

However that element is not namespace aware, so it does not know anything about the xmlns declaration that were already made outside and the XSLT thus did not output again.

Ideally I could just get to the source XML without having to embed it in the HTML. But if I have to embed it, how can I force all namespaces to be declared again?

How to make the content slide smoothly together with the sidebar?[react]

When my sidebar transitions to width: 0, the content right next to it (on its right) doesn’t slide with it. It’s like the text waits for the sidebar to be done with its animation before it takes the sidebar’s place, even though I set its transition as well.

I came up with a minimal reproducible example below:

//Sidebar.js
import './styles/Sidebar.css'

export const Sidebar = () => {
  const [show, setShow] = useState(false);
  
  const toggle = ()=>{
    setShow(!show);
}

  return (
    <div>
        <div id={'toggle-btn'}>
            <button type='button' className='toggle-btn' onClick={toggle}>
                toggle
            </button>
        </div>
        <div style={{display:"flex"}}>
            <aside className={'sidebar' + (show ? ' showSidebar':'')}>
                <ul className='menuList'>
                    <li>Perfil</li>
                    <li>Estatísticas</li>
                    <li>Adicionar Itens</li>
                    <li>Procurar</li>
                </ul>
            </aside>
        </div>
    </div>
  )
}

/*Sidebar.css*/
.sidebar {
    width:100%;
    overflow: hidden;
    box-shadow: 0 8px 8px -4px ;
    transform: translateX(0);
    transition:all 1s ease;
    height:100vh;
}
.showSidebar {
    width:0;
}

//Dashboard.js
    import './styles/Dashboard.css'
    export const Dashboard = () => {
      return (
        <div className='dashboard'>
        <p>
        LORE IPSUM BLA BLA
        </p>
       </div>
      )
    }

/*Dashboard.css*/
.dashboard {
    max-width: 30%;
    margin-top:10rem;
    transition:all 1s ease;
}

//App.js
function App() {

  return (
    <div style={{display:"flex"}}>
    <Sidebar />
    <Dashboard /> 
    </div>
  );
}

export default App;

Change property state to false depending on value of another property Mongoose Express NodeJS

I need to change the status of a property from true to false depending on whether in the property called “outstandingBalance” its value is equal to 0. For now I receive the data to make the change of “outstandingBalance” correctly but I would like it to be evaluated if its value it goes to 0 to be able to make the change automatically.

This is my code:

    const previousBalance = parseFloat(lastPayment.previousBalance);
      
    const newAmount = parseFloat(data.adjustmentAmount);

    let newOutstandingBalance = 0;

    newOutstandingBalance = parseFloat(previousBalance) + parseFloat(newAmount);  

    const updateOutstandingBalanceSale = await Sale.findOneAndUpdate( {'_id': req.creditSaleToAdjust.saleId },{
        $set: {
            'outstandingBalance': newOutstandingBalance                                        
            },
    });

In my model I have the status property that I need to change if outstandingBalance has the value of 0

My model:

const SaleSchema = Schema (
  {
    saleId: {
        type: Number,
        unique: true
    },
    user:{
          type: Schema.Types.ObjectId,
          ref:'Users',
          required: [true, 'El Usuario es obligatorio']
    },
    clientId:{
        type: Schema.Types.ObjectId,
        ref:'Client',
        required: [true, 'El Cliente es obligatorio']
    },
    notes: {
        type: String,
        maxlength:200,
    },
    subtotal: {
        type: Number,
        default: 0,
        required: [true, 'El Subtotal es obligatorio']
    },
    discount: {
        type: Number,
        default:0
    },
    tax: {
        type: Number,
        default:0
    },
    totalBeforeTax: {
        type: Number,
        default: 0,
        required: [true, 'El Total sin Impuestos es obligatorio']
    },
    total: {
        type: Number,
        default: 0,
        required: [true, 'El Total es obligatorio']
    },
    paymentType: {
        type: String,
        required: true,
        enum: ['CASH', 'CREDIT', 'TRANSFER'] 
    },
    outstandingBalance: {
        type: Number,
        default: 0,
        required: [true, 'El Adeudo Pendiente es obligatorio']
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    status: {
        type: Boolean,
        default: true,
        required: [true, 'El Estatus es obligatorio']
    }
  }  
);

Thanks for your help.