Input change event remembers the previously changed data. How to solve it?

I use the below template to create a list of some object cards. Each card has a unique doctor id and a button to book appointment. When I click the button, it works well for the first card. Then when I click the other cards, first it sends request with the clicked card’s doctor id and then with the previous cards’ ids. Is this issue caused by the change event? How to solve it?

function getDoctorTemplate(doctor){
    const $template = $($('#doctor-template').html());
    $template.find('#template-doctor-name').text(doctor.name);
    $template.find('#template-doctor-contacts').text(doctor.contactDetails);
    $template.find('#book-appointment').click(function(){
        console.log("doc id ",doctor.id);
        $('#appointment-date').change(function(){
            let doctorId = doctor.id;
            let date = $('#appointment-date').val();
            $.ajax({
                url:"schedule/doctor/search",
                method:"GET",
                data:{
                    doctorId: doctorId,
                    date: date
                },
                success: function(data){
                    console.log(data);
                    if(data.length != 0){
                        $('#appointment-hour-select').empty();
                        for(let i=data.fromHour;i<data.toHour;i++){
                            $('#appointment-hour-select').append($('<option>', {
                                value: i,
                                text: (i<10?"0"+i+":00":i+":00")
                            }));
                        }
                    }else{
                        alert("Schedule not available yet!");
                    }
                    if(data == null){
                        alert("Schedule not available yet!");
                        clearModal();
                    }
                },
                fail: function(){
                    alert("Schedule search completed with fail!")
                }
            });
        });
        clearModal();
    });
    return $template;
}

enter image description here
enter image description here

Doctor with id 34 has no item with the selected date, so it returns empty data, then the select is filled with the data of the first request. I want to “forget” the first requests data. Is this possible? When I use off or unbind for the change, the code does not work.

How to pass a js-function to django template with include?

I’m trying to include another template with a js function as variable.

{% include "einkaufsliste/components/unorderedlist.html" with items=friends clickAction="see_friend()" %}

<script>
    function see_friend(){
        var x = $(this).attr("the_item")
        console.log(x)
    }
</script>

I get $(this), but not $(this).attr(“the_item”) (returns undefined)

    <div class="col-12 col-md-11">
        <ul>
            {% for i in items %}
                <li {% if clickAction %} onclick="{{ clickAction }}" {% endif %} the_item="{{ i }}" >{{ i }}</li>
            {% endfor %}
            {% if not items %}
                <li>keine</li>
            {% endif %}
        </ul>
    </div>

Maybe that’s also not the proper way to pass a function? Any suggestions? Thanks in advance!

Java Script Button.onclick doesnt’work if wrapped in div

In my project I need to create button dynamically. I wrap it to div and this div is appeded to container called tableDoc. My problem is that in this case onclick function doesn’t work.
If my button is appended straight to tableDoc with not being wrapped to div before it works fine.

Could you tell me why onclick function doesn’t work if wrapped to div?

Example with button wrapped to div before being added to tableDoc:

 Elements.map(item=>{
           
            const div=document.createElement('div');
            ///////adding button////////////////
            var deleteButton = document.createElement("button");

            deleteButton.setAttribute('type','button');
            deleteButton.setAttribute('class',"btn-close");
            deleteButton.setAttribute('aria-label','Close');
            deleteButton.setAttribute('id',item.pk);
            deleteButton.onclick = function() { 
            alert("blabla");
          };
            //////////////////////////////////////////////////////
            div.innerHTML+=item.fields.car+'  '+item.fields.model
            div.appendChild(deleteButton); 
            tableDoc.appendChild(div);
            div.innerHTML+='<br>'


            })

secondary example with button added straight to tableDoc:

Elements.map(item=>{
           
            const div=document.createElement('div');
            ///////adding button////////////////
            var deleteButton = document.createElement("button");

            deleteButton.setAttribute('type','button');
            deleteButton.setAttribute('class',"btn-close");
            deleteButton.setAttribute('aria-label','Close');
            deleteButton.setAttribute('id',item.pk);
            deleteButton.onclick = function() { 
            alert("blabla");
          };
            //////////////////////////////////////////////////////
            div.innerHTML+=item.fields.car+'  '+item.fields.model
            tableDoc.appendChild(deleteButton);
            tableDoc.appendChild(div);
            div.innerHTML+='<br>'


            })

Prisma typescript type error when creating record

I ‘m using prisma with MySql.
When I try to create a new record (School) I get a type error in console.
I’m using a framework called Remix.run too, but it shouldn’t be the problem.

I’ve tried using mongoDB too, but i got the same type error.

Error

251 console.log(info);
252 });
253 let data = {school_code: key, otp: code};
→ 254 await db.schools.create({
    data: {
        school_code: 'ISP0TMORECNJS9TB',
        ~~~~~~~~~~~
        otp: 'EMI5DU'
    }
})

Unknown arg `school_code` in data.school_code
for type schoolsCreateInput.Available args:

    type schoolsCreateInput {
        id ? : String
        v ? : Int | Null
        otp: String
    }

Prisma schema

datasource db {
    provider = "mysql"
    url = "mysql://root@localhost:3306/myeducatio"
}

model schools {
    otp String @db.Text
    school_code String @id
}

Code

Method 1

let data: any = {
    school_code: key,
    otp: code
};

await db.schools.create({
    data,
});

Method 2

await db.schools.create({
    data: {
        school_code: key,
        otp: code
    }
});

How does prevState in new useState in React work ?? How does it store the value of previous state?

I know how to use prevState in new State, I want to know how does it actually works ?? How does this functionality works ?? why on putting in ‘prevValue’ in ‘setFullName’ function changes its value ?

import React, { useState } from "react";

function App() {
  const [fullName, setFullName] = useState({
    firstName: "",
    lastName: ""
  });

  function handleChange(event) {
    let value = event.target.value;
    let name = event.target.name;

    setFullName((prevValue) => {
      if (name === "fName") {
        return {
          firstName: value,
          lastName: prevValue.lastName
        };
      } else if (name === "lName") {
        return {
          firstName: prevValue.firstName,
          lastName: value
        };
      }
    });
  }

  return (
    <div className="container">
      <h1>
        {fullName.firstName} {fullName.lastName}
      </h1>
      <form>
        <input onChange={handleChange} name="fName" placeholder="First Name" />
        <input onChange={handleChange} name="lName" placeholder="Last Name" />
        <button>Submit</button>
      </form>
    </div>
  );
}

export default App;

Mocha / Webpack: Cannot use import statement outside a module

I’m new to Node and JS Testing. I have a web applications w/ Webpack as a bundler. I have some entry point JS’s which are included into the page. The entry points are using module files like this:

export default function() {
    ...
}

Now I would like to Unit test this module. I have picked up Mocha but it is not critical to me. Could be Jest or anything else.

I wrote a very simple test.js like this. It it not doing anything but tests if the entire setup works:

import foo from '../js/someModuleOfMine'

const assert = require('assert')

describe('Test Suite', () => {
    it('should at least run', () => {
        assert.equal(true, true)
    })
})

executing mocha from CLI gives me this error:

import foo from '../js/someModuleOfMine'
^^^^^^

SyntaxError: Cannot use import statement outside a module

Adhering to some advises I have tired to add "type": "module" to my package.json but it only changed error to something even more obscure:

Error: Not supported

I am definitely missing something obvious but I cannot comprehend what.

How to pause JS script execution until button is clicked

I am making a chess game by JS. When the pawn reaches last square it should be promoted to either of four pieces . I set its display to block to show the icon of those four. What I want is to pause the JS execution until one of the piece icon is clicked. Cause after the piece becomes (say queen) I have to check if it is giving check and calculate possible moves. If i use simple onclick function I have to copy those executions again in onclick function.

So simply I am looking for piece of code that stops the script execution until user selects a piece.

Remove Play on Click and add auto play when webpage loads

I need to have a Vimeo Video play when the webpage loads, it is an example of our Community Channel and the page is not listed nor is there any audio. I am using a fullscreen loop script currently that when you go to the page had a spot for you to click to start the video… I need to change this. I have added the Script in question.

$(document).ready(function(){
  // Initiate FitVid.js
  $(".video-container").fitVids();

  // Iframe/player variables
  var iframe = $('#video')[0];
  var player = $f(iframe);

  // Open on play
  $('.play').click(function(){
    $('.overlay').css('left', 0)
    $('.overlay').addClass('show')
    player.api("play");
  })

  // Closes on click outside
  $('.overlay').click(function(){
    $('.overlay').removeClass('show')
    setTimeout(function() {
      $('.overlay').css('left', '-100%')
    }, 300);
    player.api("pause");
  })
});

What does ‘object.function’ means in Javascript?

I have quite a hard time understanding this expression (split in italic) Can someone explain it to me:
I understand ‘this’ referring to an object but in this case then what does ‘object.function’ means ?

class Chronometer {
  constructor() {
   this.currentTime = 0
   this.intervalId = null
  }

getMinutes() {
    return this.currentTime/60
  }

 getSeconds() {
    return this.currentTime%60
  }

computeTwoDigitNumber(value) {
     return String("0" + value).slice(-2)
  }

*split () {
      var minutes = this.computeTwoDigitNumber(this.getMinutes());
      var seconds = this.computeTwoDigitNumber(this.getSeconds());
      printSplit(minutes, seconds)*

Get mongoose data when matched all object in array?

I have search everywhere, but not getting any solutions. Can anyone help?

I have a mongoose object like image-

enter image description here

Here I also get a array of product from frontend like-

products: [
    { product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
    { product: "61adbb52207f1002fc7c5c27", quantity: 2 }
  ]

I have to find mongoose data when all the product match to the queries.

Here is my practice-

         const order = await Order.exists({
            products: {
                $all: {
                    $elemMatch: {
                        product: {
                            $all: input.products.map(item => item.product)
                        }
                    }
                }
            },
            user: reqUserInfo._id
        });

More description–

When I get from frontend this-

      products: [
        { product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
        { product: "61adbb52207f1002fc7c5c27", quantity: 2 }
      ]

then it should return true

And when I get this-

          products: [
            { product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
          ]

It also should return true.

But When I get this-

      products: [
        { product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
        { product: "61b3786ba2123f03dc6da691", quantity: 2 } // This not in the database
      ]

or This

      products: [
        { product: "61b37850a2123f03dc6da68e", quantity: 1 }
        { product: "61b3786ba2123f03dc6da691", quantity: 2 }
        //This two are not in the database
      ]

Then should return false

How can I do that? Please help me.

Can’t make an IMAGE fit in Material CardMedia something is of I cant find it please advice

I learn JavaScript React and now I have problem with positioning of images.
I have a Codesandbox.

I learn from this MUI tutorial.

It should look like this this but I get bad output.

enter image description here

In the Component FileEditor.jsx I load up the FileContentRenderer.jsx that can show both MP4 and Images, but images has problem.
In the FileContentRenderer.jsx I try this:

  cardMedia: {
    width: "auto",
    height: "100%"
  }

That should show the image but not,
Then I try this;

  cardMedia: {
    width: "100%",
    height: "50vh"
  }

That will display images in portrait but in landcape it does not show full image.

This viewer App can display MP4 and images and the MP4 is showing ok in landscape and portrait when using

  viewerMp4: {
    width: "auto",
    height: "100%"
  },

So why does that not work with an image

rendering username or id in the url with express routing

I have read some documentation on express routing and I am trying to render the logged in user’s username or identification in the url. I need help getting the routing hit in my server.js to render the pages even before authentication. Where am I messing up?

Routing (profile.js)

const express = require("express");
var router = express.Router();
const User = require("../models/user");
const passport = require("passport");
const multer = require("multer");

// Profile Avatar
const upload = multer({ dest: "upload" });
// ACCOUNT ROUTES

router
  .route("/profile/:id")
  .get(function (req, res) {
    if (req.isAuthenticated()) {
      let dateObj = req.user.createdAt;
      let createdDate = dateObj.toString().slice(4, 16);
      let navbarLoggedIn = "partials/loggedIn-navbar.ejs";
      let id = req.params.username;
      console.log(id + "n");
      res.render(
        "profile",
        { id: req.params.id },
        {
          currentUser: req.user.username,
          currentCompany: req.user.company,
          currentLocation: req.user.location,
          currentPosition: req.user.position,
          memberStatus: createdDate,
          navbar: navbarLoggedIn,
        }
      );
    } else {
      res.redirect("login");
    }
  })
  .post(function (req, res) {});

module.exports = router;

server.js

require("dotenv").config();
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const path = require("path");
const ejs = require("ejs");
const logger = require("morgan");
const main = require("./routes/main");
const about = require("./routes/about");
const contact = require("./routes/contact");
const profile = require("./routes/profile");
const pricing = require("./routes/pricing");
const help = require("./routes/help");
const login = require("./routes/login");
const signup = require("./routes/signup");
const forgot_password = require("./routes/forgot-password");
const User = require("./models/user");
const multer = require("multer");

// PORT
const port = 8080;
const app = express();

// COOKIES AND SESSION
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: true,
  })
);

app.use(passport.initialize());
app.use(passport.session());

// DATABASE
require("./config/database.js");

// PASSPORT AUTHENTICATION
require("./config/passport.js");

// MIDDLEWARE
app.use(logger("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use("/public", express.static(path.join(__dirname + "/public")));
app.set("view engine", "ejs");
app.set("view cache", false);

// ROUTES
app.use("/", main);
app.use("/about", about);
app.use("/contact", contact);
app.use("/pricing", pricing);
app.use("/profile/:id", profile, (req, res, next) => {
  next();
});
app.use("/help", help);
app.use("/login", login);
app.use("/signup", signup);
app.use("/forgot-password", forgot_password);



// Logout
app.get("/logout", function (req, res) {
  res.clearCookie("connect.sid");
  res.redirect("/");
});

app.listen(port, (err, done) => {
  if (!err) {
    console.log({ message: "success!" });
  } else {
    return err;
  }
});

And here is my file structure.file structure.