Best way to develop this function in react js instead of this current .map

first of all i am new to all this, so apologies. I am trying to develop a search function, now i have developed it but as to my app there is a problem.

The search function which is in my header component is rendered like this in my index

<Header course={course}/>

which does not work as i get “cannot get property of slug” which is here in the header component

import React, { useState, useEffect } from "react";
import Link from "next/link";
import {
  ShoppingCartIcon,
  MenuIcon,
  SearchIcon,
} from "@heroicons/react/outline";
import { useRouter } from "next/router";
import * as Realm from "realm-web";

const Header = ({course}) => {
  const {slug } = course;
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [autoComplete, setAutoComplete] = useState([]);

  useEffect(async () => {
    if (searchTerm.length) {
      // add your Realm App Id to the .env.local file
      const REALM_APP_ID = process.env.NEXT_PUBLIC_REALM_APP_ID;
      const app = new Realm.App({ id: REALM_APP_ID });
      const credentials = Realm.Credentials.anonymous();
      try {
        const user = await app.logIn(credentials);
        const searchAutoComplete = await user.functions.searchAutoComplete(
          searchTerm
        );
        setAutoComplete(() => searchAutoComplete);
      } catch (error) {
        console.error(error);
      }
    } else {
      setAutoComplete([]);
    }
  }, [searchTerm]);

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

    setSearchTerm("");
    router.push({
      pathname: `/search/${searchTerm}`,
    });
  };

  const handleSelect = (id) => {
    setSearchTerm("");
    router.push({
      pathname: `/course/${slug}`,
    });
  };

  return (
    <>
      <header>

            <form onSubmit={handleSubmit}>
              <input
                className="w-full border rounded-md pl-10 pr-4 py-2 focus:border-green-500 focus:outline-none focus:shadow-outline"
                type="text"
                placeholder="Search"
                onChange={(e) => setSearchTerm(e.target.value)}
                value={searchTerm}
              />
            </form>
            {autoComplete.length > 0 && (
              <ul className="absolute inset-x-0 top-full bg-green-200 border border-green-500 rounded-md z-20">
                {autoComplete.map((item) => {
                  return (
                    <>
                    <li
                      key={item.slug}
                      className="px-4 py-2 hover:bg-green-300 cursor-pointer"
                      onClick={() => handleSelect(item.slug)}
                    >
                      {item.name}
                    </li>
                    </>
                  );
                })}
              </ul>
            )}
          </div>
        </div>
      </header>
     
    </>
  );
};

export default Header;

Now in my index file it should be something like this:

 <Header course={course}/>

But i have to put it in a map function and it does not work properly like that,

  {courses.map((course) => (
                <div className="col-md-4">
                 {/* <Cards course={course} /> */}
                 <Header course={course}/>
                </div>
            ))}

So can you guys tell me or show me what type of function i need to use so that my identifiers, args whatever can work and my search index with slug will work

How to fix the graphing line on math calculator with initial scale

Im currently building an math graphing calculator in discord.js, the graphing work fine on 1.0x scale but when im changing the scale the graphing line start not right with the axes,
I saw it to be move to bottom-left not to be the center of the graph

function draw(tree) {
    var i = 0;
    dx = 1 / global_scale;

    var y;
    variables.x = minX;

    var width = canvas.width;

    while (isNaN((y = eval(tree))) && i < width) {
        variables.x = minX + i * dx;
        i++;
    }

    let previousY = (y - minY) * global_scale;

    for (; i < width; i++) {
        variables.x = minX + i * dx;
        y = eval(tree);

        if (isNaN(y)) {
            console.log(`discontinuity at x = ${x}`);
            while ((y = eval(tree)) === NaN && i < width) {
                variables.x = minX + i * dx;
                i++;
            }
            previousY = (y - minY) * global_scale;
            continue;
        }

        y = (y - minY) * global_scale;

        ctx.beginPath();
        ctx.moveTo(i - 1, previousY);
        ctx.lineTo(i, y);
        ctx.lineWidth = 2;
        ctx.stroke();
        previousY = y;
    }
}```

[The graphing when i do x^2 with 0.01 initial scale][1]

[The graphing when i do sin(x) with 0.01 initial scale][2]


and i wanna it to be something like this :
[The graphing when i do x^2 with 1.0 initial scale][3]


  [1]: https://i.stack.imgur.com/WTTl6.png
  [2]: https://i.stack.imgur.com/8fH4n.png
  [3]: https://i.stack.imgur.com/hefWl.png

How to use lodash uniq instead of new Set using javascript?

Hi i want to use lodash uniq instead of new Set for the case below,

const checkForMultipleItems = (ids) => {
    const rex = /component/(d+)//;
    const multipleIds = 
        itemIds
        .map(str => (str.match(rex) ?? [])[1])
        .filter(result => result !== undefined);
    return new Set(multipleIds).size !== 1; //replace with uniq
}


const isMultiple = checkMultipleIds(ids);

for the above code how can i replace new Set with lodash uniq could someone help me with this? thanks.

So let me introduce

They saved you Alright MIC 11 windows insiders dev job.

My name is Joey van Bree Learning full stack development from html 5 – software testing
All the books on the shelter. Praying one day i can work again without people inspect en do not even care to say the least about my personal space. Call*** Privacy

Hi Google Still I thought that I Google Van Zieber country Could explain English patriotic song in fact It needs to be using How do people come to you Christophers Lyrics to seals farewell rights Christopher Holst Who are the insults here Presbyterian Excellent Who the flying dishman Who are the flying dishmen What are the flight dish mounts Ozzy Osbourne Looking at themselves Who is the creative Rescreened The screen Who is the beer teeth Teach Teach Who is the big teeth With big teeth With a big tooth Doubt Coverage Coco roach In a nutshell Right now Yes Lol @ mic me

Tiger of gold
Aka Joey van Bree
Owner
Free and no more hunger privacy and global goals etc..

Just an hello world
My bad

i want call a function when click close browser … element of button close browser?

This is my javascript code …i want call a function when click close browser at window.close().But not working..You can help me.Thank so much.<3

<script>
            $(document).ready(function () {
                var typeChange = false;
                $(document).on("keyup", 'form input', function (e) {
                    typeChange = true;
                });
                $(document).on("change", 'form select', function (e) {
                    typeChange = true;
                });
                function changeURL() {
                    window.addEventListener("beforeunload", function (e) {
                        if (typeChange) {
                            e.preventDefault(); 
                            e.returnValue = "";  
                        }
                    }, {once : true});
                }
               
                $(document).on('click', '.sidebar-menu a', function() {
                    changeURL();
                });
                // window.addEventListener("close", function () {
                //     changeURL();
                // });

                // window.close() = function() {
                //     changeURL();
                // };

            });
        </script>

Simple renaming – remove (JOB_0000_) from file name

I work with software that generates an output files with the names: JOB_1_sample-file_20220211083122.txt in a specific folder. There are thousands of files at the same time.

The beginning of the text file is variable (JOB_1,JOB_2,JOB_3,etc).

Example: JOB_2_sample-file_20220211083122.txt, JOB_34_sample-file_20220211083122.txt, JOB_1007_sample-file_20220211083122.txt.

I need to remove the initials from the files, leaving only the ‘sample’ forward.
Preferably using Powershell, CMD or javascript.

Is there such a possibility?

When even i click on particular day of all shifts it has it highlish the all shifts in that day

i have created a page using html css and javascript. in this page i am showing like shift information for week.

i had options like 4AM 8AM 1PM 6PM and show all shifts.

when user click on all shifts it has to highlisht the allshift in that particular day but here i am facing issue like when i click on Monday all shifts it is highliting but after when i click on tuesday it highliting both Monday and Tuesday.

My requirement is when i click on particular day that one only has to higlight.

Please find my Code and images below.

<div class="row">
              <div class="col-2"></div>
              <div class="col-2">
                <p>
                  Early shifts<br /><span class="text-primary"
                    >starting at 4AM +</span
                  >
                </p>
              </div>
              <div class="col-2">
                <p>
                  Day shifts<br /><span class="text-primary"
                    >starting at 8AM +</span
                  >
                </p>
              </div>
              <div class="col-2">
                <p>
                  Afternoon shifts<br /><span class="text-primary"
                    >starting at 1PM +</span
                  >
                </p>
              </div>
              <div class="col-2">
                <p>
                  Night shifts<br /><span class="text-primary"
                    >starting at 6PM +</span
                  >
                </p>
              </div>
              <div class="col-2">
                <p>
                  All day<br /><span class="text-primary"
                    >show me all shifts</span
                  >
                </p>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Mon</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="mon-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="mon-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="mon-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="mon-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="mon"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Tue</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="tue-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="tue-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="tue-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="tue-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="tue"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Wed</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="wed-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="wed-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="wed-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="wed-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="wed"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Thu</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="thu-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="thu-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="thu-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="thu-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="thu"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Fri</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="fri-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="fri-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="fri-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="fri-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="fri"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Sat</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="sat-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="sat-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="sat-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="sat-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="sat"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>
            <div class="row">
              <div class="col-2">
                <p>Sun</p>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-low"
                  style="font-size: 2rem"
                  id="sun-4am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-alt-high"
                  style="font-size: 2rem"
                  id="sun-8am"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-brightness-high"
                  style="font-size: 1.5rem"
                  id="sun-1pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-moon"
                  style="font-size: 1.35rem"
                  id="sun-6pm"
                ></i>
              </div>
              <div class="col-2 text-center">
                <i
                  class="bi bi-arrow-clockwise"
                  style="font-size: 1.65rem"
                  id="sun"
                  onclick="changeBG(this.id)"
                ></i>
              </div>
            </div>

Javascript code is

function changeBG(id) {
    function returnId(id) {
      return id;
    }
    const elementId = returnId(id);
    // console.log(elementId);
    var mon4am = document.getElementById(`${elementId}-4am`);
    var mon8am = document.getElementById(`${elementId}-8am`);
    var mon1pm = document.getElementById(`${elementId}-1pm`);
    var mon6pm = document.getElementById(`${elementId}-6pm`);
    // monBlock.style.backgroundColor = "red";
    mon4am.style.color = "#DEC20B";
    mon8am.style.color = "blue";
    mon1pm.style.color = "green";
    mon6pm.style.color = "red";
  }

Please find the below images

enter image description here

enter image description here

Infinite Loop creates duplicate instances on cloneNode(true)

I am trying to create a carousel that has an infinite loop.. where the first item re-appears after the last item.. So basically I have 10 logos that are passing through an view.. so I am trying to move them one by one.. and as they move the one of the left gets deleted by node.removeChild(x) and I am trying to add with cloneNode(true) at the end of the list of items.

So I expected the list to always be 10 items as one gets removed and one gets added.. however there seems to be 2 of the same items getting added each time one gets deleted. I have tried to understand this by console.log process and it seems that when I delete too the console.log happens twice. I can’t seem to figure out why. I’ve spent almost 2 days trying to figure this out on my own. I would appreciate some advice on understanding what I am doing wrong.

Please find below my HTML, CSS, and JS and here’s a link to the codepen (https://codepen.io/alimbolar/pen/yLPzERj?editors=1111)

HTML

<main>
<section>
  <article class="carousel">
    <ul class="carousel__list">
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/bvlgari-logo-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/champion-logo-400x200.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/chopard-Logo-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/clem-margaux-logo-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/eagle-eyes-optics-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/exalt-cycle-logo-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/lindberg-logo-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/maui-jim-logo-400x200px.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/l1H1OU-400x200.jpg" alt=""></picture></figure></li>
      <li class="carousel__item"><figure><picture><img src="https://storage.googleapis.com/alimbolar-bucket/data/public/assets/images/logo/silhouette-Logo-400x200px.jpg" alt=""></picture></figure></li>
 
    </ul>
  </article>
</section>
  </main>

CSS

html{
  box-sizing:border-box;
}

*,*:before,*:after{
  box-sizing:inherit;
  margin:0;
  padding:0;
}

img{
  max-width:100%;
  height:auto;
}
body{
  background:grey;
  display:flex;
  justify-content:center;
  align-items:center;
  width:100%;
  height:100%;
}

main{
  width:80%;
  // height:100px;
  background:white;
  display:flex;
  justify-content:center;
  align-items:center;
  section{
    
    border:1px solid maroon;
    padding: 1rem;
  }
}
.carousel{
  width: 500px;
  height:80px;
  // overflow:hidden;
  &__list{
    display:flex;
    // gap:1em;
    position:relative;
  }
  &__item{
    position:absolute;
    padding:0.4rem;
    top:0;
    left:0;
    transition: all 1s;
    width:100px;
    border:1px solid gray;
    
  }
}

JS

const list = document.querySelector('.carousel__list');
let items = list.querySelectorAll('.carousel__item');


function goToSlide(x=0){
  let items = list.querySelectorAll('.carousel__item');
  items.forEach((item,index)=>{
    item.style.transform = `translatex(${(index-x) * 100}%)`
  }); 
}

function addSlide(){
  let items = list.querySelectorAll('.carousel__item');
  const newItem = items[0].cloneNode(true);
  list.appendChild(newItem);
}

function removeSlide(){
  list.removeChild(list.firstChild)
}

// INIT FOR FIRST POSITION AT POSITION 0 BY DEFAULT

goToSlide();

///// FOR SETTIMEOUT IF IT IS USED
// function play(){
//   goToSlide(1);
//   removeSlide();
//   addSlide();
//   setTimeout(play,2000);
// }

// play();

setInterval(function(){
  addSlide();
  goToSlide(1);
  removeSlide();
},2000)





``

An error has occurred. See error log for more details. com/sap/mw/jco3/eclipse/Registry

Attempting to open SAP HANA BW in Eclipse IDE 09-21 application. The following error occurs: An error has occurred. See error log for more details.
com/sap/mw/jco3/eclipse/Registry

There are several unhandled loop exceptions in org.eclipse.ui. I attempted to paste the code but received an error when I pasted the code in the body.

Any feedback to resolve this error is appreciated.

Jest: Can’t extract function that mocks a module

I’m trying to find a simple and reusable way to mock responses from http requests. Right now I have:

// foo.test.ts 

jest.mock('axios');
import axios from 'axios';

describe('when updating user', () => {
  beforeEach(() => {
    (axios.post as jest.Mock).mockReturnValue({
      data: updatedUser,
    });
    result = foo();

But I’d rather simply pass my expected return value to a function I can reuse throughout my application:

// foo.test.ts

import { mockPost } from './mock'

describe('when updating user', () => {
  beforeEach(() => {
    mockPost(updatedUser);
    result = foo();
  })

So I tried to extract this mock into another module like so:

// mock.ts

jest.mock('axios');
import axios from 'axios';

export function mockPost(item: unknown) {
  (axios.post as jest.Mock).mockReturnValue({
    data: item,
  });
}

But alas, the module is no longer mocked. Is this impossible and if so, why?

React native and Gifted Chat : Error with firestore

I’m using React Native with JS.
I would like to add a chat screen using Gifted Chat.

But I’m facing an error every time the user navigate on this screen.
I put the wrong part of the code inside a try. Now, the app doesn’t crash anymore but returns this error when the user send a chat :

Cannot read properties of undefined (reading 'startAt')
at node_modules/@firebase/firestore/dist/lite/index.rn.esm2017.js:4666:27 in <global>
at node_modules/@firebase/firestore/dist/lite/index.rn.esm2017.js:4665:18 in <global>
at node_modules/@firebase/firestore/dist/lite/index.rn.esm2017.js:4562:29 in Ke#get
at Liste/ServiceDescription.js:14:29 in ServiceDescription

Here is the bugged part, it has to return the data present on firebase to put them in an array [messages]. I’m using query and orderBy to order them by date :

useLayoutEffect(() =>  {
  try {
  const collectionRef = getDocs(collection(database, 'ChatSended', uid, idUserService));
  const q = query(collectionRef, orderBy('createdAt', 'desc'));

  const unsubscribe = onSnapshot(q, snapshot => {
    console.log('snapshot');
    setMessages(
      snapshot.docs.map(doc => ({
        _id: doc.id,
        createdAt : doc.data().createdAt,
        text: doc.data().text,
        user: doc.data().user,    
      }))
    )
});
return unsubscribe;
  } catch (err) {
  console.log(err);
}
  
}
, []);

Inside node_module, the part of the code concerned is this one :

class ir extends nr {
    constructor(t, n) {
        super(), this.dt = t, this._t = n, this.type = "orderBy";
    }
    _apply(t) {
        const n = function(t, n, e) {
            if (null !== t.startAt) throw new k(A, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
            if (null !== t.endAt) throw new k(A, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
            const r = new sn(n, e);
            return function(t, n) {
                if (null === hn(t)) {
                    // This is the first order by. It must match any inequality.
                    const e = ln(t);
                    null !== e && gr(t, e, n.field);
                }
            }(t, r), r;
        }

In this line :

if (null !== t.startAt)

Can you please help me ?
Thanks !

Loop to HTML text, replace tags with another value

I am creating a custom message desktop app, that will enable people customize messages. I mean replace the tags in the message with data the have inserted in the app. But my java script code is unable to replace the tags with the data.

Here is an example of the custom message template:

Dear , You are cordially invited to our naming ceremony on the . We are glad to inform you that you have been employed by . We say congrats.
Thank you for opening an account with Great Bank, Your account number and password can be found below.
Account number :
Password :

Here is a good example: The name tags should be replaced by the name of the individual,etc.

I am using regex

here is the ouput: I get an unedited message

The output

Update but ignore form data when update to mysqwl

I’m pretty new to programming. Or, years ago I started with mysqli and php. But now I started again.
And there is a whole new area. I use ajax to process form data. I am updating user information.
Everything is going great, until when accessing email verification. There is no problem registering, or adding a user.
Because the old data is not an email that is fetching from the database.
Now that the data is fetching from the database for the form, and when I try to edit it, checking that the email already exists will also check the information which is already on this form.
That is, when I check to see if the email already exists, it also checks the email in the form. Can I with ajax somehowe check if input field is changed, or what I should do?
And yes, I know that I should use pdo, but first I want to learn the whole thing (ajax, javascript etc.).
My english is not so very good, but I hope you get something clear.

Sorry if a different language in code brings confusion.
Database connection function is not essential. There are no errors. So I’m not putting it here now.

This is the first question I ask in this forum. So be patient.

Here is html form

                <div class="modal-body">
                <div id="valid-email"></div>
                <div id="valid-email-muutos"></div>

                <div id="loytyyko-email-edit"></div>
                    <form method="post" id="muokkaa_kayttaja">  
                    <div class="row">
                    <div class="col-md-6 mb-3 mb-md-0">
                        <label>Etunimi <!--Firstname--></label><span class="error"> *</span><span class="error" id="add-virhe-etunimi"></span>
                        <input type="text" name="edit_etunimi" class="form-control etunimi" value='<?php echo htmlspecialchars($row1['etunimi']);?>' />
                    </div>
                    <div class="col-md-6 mb-3 mb-md-0">
                        <label>Sukunimi <!--Lastname--></label><span class="error"> *</span><span class="error" id="add-virhe-sukunimi"></span>
                        <input type="text" name="edit_sukunimi" class="form-control sukunimi" value='<?php echo htmlspecialchars($row1['sukunimi']);?>' />
                    </div>
                    <div class="col-md-6 mb-3 mb-md-0">
                        <label>Sähköposti <!--email--></label><span class="error"> *</span></span><span class="error" id="add-virhe-email"></span>
                        <input type="text" name="edit_email" id="edit_email" class="form-control email" value='<?php echo htmlspecialchars($row1['email']); ?>' />
                    </div>
                    <div class="col-md-6 mb-3 mb-md-0">
                        <label>Yritys <!--company--><small>(valinnainen)</small></label>
                        <input type="text" name="edit_yritys" class="form-control yritys" value='<?php echo htmlspecialchars($row1['yritys']);?>'  />
                        </br>
                    </div>
                    <div class="col-sm-12">
                        <label>Haluatko muuttaa käyttäjän ylläpitäjäksi? <!--make admin?--><small>(valinnainen)</small> </label></br>
                        <p></p><input type="checkbox" class="valittu" name="yllapito"  value="1"> Kyllä, muuta ylläpitäjäksi</p>
                       </br> 
                 </div>
                    <input type="hidden" name="kayttaja_id" value='<?php echo $row1['kayttaja_id'];?>' /> <!--user_id-->

                    <div class="col-md-6 mb-3 mb-md-0">
                         <input type="submit" name='tallentaa' class="btn btn-success"  value='Tallenna' /><!--save button-->
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Peruuta <!--Cancel button--></button>
                    </div>
                    </form>
                </div>
           </div>  
      </div>
</div>

Ajax

$(document).ready(function(){  
      $('#muokkaa_kayttaja').on("submit", function(event){  
           event.preventDefault();

            var kayttaja_id = $("#kayttaja_id").val();
            var etunimi = $("#etunimi").val();
            var sukunimi = $("#sukunimi").val();
            var yritys = $("#yritys").val();
            var email = $("#email").val();
            var yllapito = $("#yllapito").val();

            //is admin checked
            $('.valittu').each(function () {
                var id = $(this).attr('id');
                if ($('#' + id).prop('checked')) {
                    var yllapito = $("#yllapito").val('1');
                    }
            });
            //a variable is defined as true (if there are no errors) 
            var isValid = true;
        //firstname cannot be empty
        if(etunimi === ''){
            isValid = false;
            $("#add-virhe-etunimi").html(' pakollinen');
        }else{
            $("#add-virhe-etunimi").html("");
        }
        //email cannot be empty
        if(email === ''){
            isValid = false;
            $("#add-virhe-email").html(' pakollinen');
        }else{
            $("#add-virhe-email").html("");
        }
        //surname cannot be empty
        if(sukunimi === ''){
            isValid = false;
            $("#add-virhe-sukunimi").html(' pakollinen');
        }else{
            $("#add-virhe-sukunimi").html("");
        }

            //if not mistakes, isValid is true
            if(isValid === true){
 
                $.ajax({  
                     url:"muokkaakayttaja.php", //edit user php-file
                     method:"POST",  
                     data:$('#muokkaa_kayttaja').serialize(), 
                     success:function(data){
                                                  
                    if (data == 'taken' ) {
                    $("#loytyyko-email-edit").html('<div class="alert alert-danger text-center">Sähköposti on jo käytössä toisella käyttäjällä!</div>'); 
                    return false;
                    }else{
                    $('#loytyyko-email-edit').html('');
                      window.location = window.location.href; 
                        }
                     }  
                });  
           }  
      }); 
});  

And php

        //variables
        $email = mysqli_real_escape_string($con, $_POST['email']);
        $etunimi = mysqli_real_escape_string($con, $_POST['etunimi']);
        $sukunimi = mysqli_real_escape_string($con, $_POST['sukunimi']);
        $yritys = mysqli_real_escape_string($con, $_POST['yritys']);
        $sukunimi = ucfirst($sukunimi);
        $etunimi = ucfirst($etunimi);
        $yllapitoyp = mysqli_real_escape_string($con, $_POST['yllapito']);

        $kayttaja_id= mysqli_real_escape_string($con, $_POST['kayttaja_id']);
  
        //if admin is selected then 1
        if($yllapitoyp == '1')
        {
            $yllapito = '1';
        }
        //if admin is not slected then 0
        else
        {
            $yllapito = '0';
        }

        //get db email
        $kannan_email = mysqli_query($con, "SELECT email FROM kayttaja WHERE email IN  (SELECT email FROM kayttaja WHERE email =('".$email."')) AND email IN (SELECT email FROM kayttaja WHERE email NOT IN ('".$haettu_email."'))");
        if(mysqli_num_rows($kannan_email) > 0) 
        {
            echo "taken";
            return false;
        }
        else
        {
            //Update user
            $tulos = mysqli_query($con,"UPDATE kayttaja SET etunimi = '".$etunimi."', sukunimi='".$sukunimi."', email = '".$email."',  yritys = '".$yritys."', yllapito = '".$yllapito."' WHERE kayttaja_id = '".$kayttaja_id."'") or dIE();
       
            if($tulos)
            {
                //set in session notification (Update successful)
                echo $_SESSION['success'] = "<script type='text/javascript'>toastr.success('Tiedot tallennettu')</script>"; 
            }
            else
            {
                //set in session notification (sometihing gone wrong)
                $_SESSION['error'] = "<script type='text/javascript'>toastr.error('Jotain meni vikaan, yritä uudelleen')</script>";
                return false;
            }
        }
    }


Listen to ‘onInvalid’ HTML event for a

I would like to add an event listener for when a user tries to submit a <form> that has validation errors.

Is there a way to do that in a reliable and accessible way?

Solutions I considered (none of them are good):

  1. Adding ‘submit’ event listener to <form>.

    This doesn’t work since ‘submit’ is only fired for valid forms.

  2. An ‘invalid’ event is fired by HTML <input> elements that have validation errors when
    the user tries to submit a form.

    The event does not bubble, so I can’t listen to it like this: form.addEventListener('invalid', callback);

    Thus, listening for ‘invalid’ event requires adding ‘invalid’ event listener for each <input> inside the form when that field is created. It is easy to forget to add an event listener to a field, since fields are created dynamically in many different .js and .tsx files, thus this solution is error-prone and far from ideal.

  3. Listening for ‘click’ event on the submit button and in the callback checking if form.checkValidity() is false.

    This solution is also not ideal as screen reader software and other assistive technologies won’t necessarily trigger the ‘click’ event when trying to submit the form.

Is there any good way to know if a user tries to submit an invalid form?

I am fine with a solution that involves React, jQuery or native JavaScript.


If there is no good to this problem, please consider my use case and tell if there is an alternative approach:

I need to add styling to invalid form fields only after the user tried to submit a form.