Angular CDK Drag and Drop with Nested Arrays: previousIndex Always 0 When Dragging to Top, Works Correctly When Dragging to Bottom

I’m working with Angular CDK’s Drag and Drop on nested arrays and encountering an issue with sorting the items. Specifically, when I drag an item to the top of a list, the previousIndex provided by the CdkDragDrop event is always 0, which is incorrect. However, dragging an item to the bottom of the list updates the previousIndex correctly. This issue occurs in a nested drag-and-drop setup, and I’m not sure why the behavior differs based on the drop position.

I’ve checked that cdkDrag and cdkDropList directives are correctly applied.
Ensured that cdkDropListData is properly bound to the nested array.
Logged the event object to inspect previousIndex and currentIndex values.
Despite these checks, dragging to the top of the list always results in previousIndex being 0. Dragging to the bottom, however, gives the correct previousIndex.

Expected Behavior:
The previousIndex should accurately reflect the original position of the dragged item, regardless of whether it’s dragged to the top or bottom of the list.

Actual Behavior:
previousIndex is always 0 when dragging to the top but correct when dragging to the bottom.

Any insights or suggestions to resolve this issue would be greatly appreciated!

<div *ngIf="item">
    <div cdkDropList class="item-dropzone parent" [id]="parentItemId"
        [cdkDropListData]="parentItem" [cdkDropListConnectedTo]="allDropListsIds">

        <div cdkDrag [id]="item.uId" [cdkDragData]="item" [cdkDragDisabled]="dragDisabled 
            || item.folderName === 'Global Predefined Searches' && !isGlobalUser" class="drag-item">
                
            <div title="Drag this item with children" class="item-drag-handle" cdkDragHandle
                [ngClass]="{'expanded': item.expanded,'collapsed': !item.expanded}">

                <i *ngIf="!dragDisabled && item.folderName !== 'Global Predefined Searches' && !isGlobalUser
                || !dragDisabled && item.folderName === 'Global Predefined Searches' && isGlobalUser 
                || !dragDisabled && item.folderName === 'Saved Searches' && isGlobalUser" class="material-icons">
                    drag_indicator
                </i>

                <mat-icon cdkDrag *ngIf="item.expanded && item.nested" aria-hidden="false"
                    (click)="toggleHeight(item.uId, item.expanded)" aria-label="expanded" aria-describedby="expanded"
                    aria-labelledby="expanded" class="material-icons-outlined saved__indeterminate ">
                    indeterminate_check_box
                </mat-icon>

                <span *ngIf="!item.expanded && item.nested" aria-hidden="false" aria-label="expand"
                    (click)="toggleHeight(item.uId, item.expanded)" aria-describedby="expand" aria-labelledby="expand"
                    class="material-icons-outlined">
                    add_box
                </span>

                <mat-icon
                    *ngIf="item.folderName === 'Global Predefined Searches' && isGlobalUser || item.folderName === 'Saved Searches'"
                    (click)="editFolderName($event, item.name, item.uId, item.name, item)" aria-hidden="false"
                    aria-label="edit folder name" aria-describedby="edit folder name"
                    aria-labelledby="band-button-2 band-text-2" class="search">
                    search
                </mat-icon>

                <span *ngIf="item.nested" aria-hidden="false" aria-label="folder" aria-describedby="folder"
                    aria-labelledby="folder" class="material-icons-outlined folder">
                    folder
                </span>

                <div (click)="searchToEdit($event, item, item.nested)" class="search-btn" [ngClass]="{ 'search-btn__selected' : item.isSelected && item.folderName !== 'Global Predefined Searches' || isGlobalUser && item.isSelected && item.folderName === 'Global Predefined Searches',
                     'search-btn__clickable' : !item.nested}">
                    {{item.name}}
                </div>

            </div>

            <div class="item-drag-preview" *cdkDragPreview>
                {{item.name}}
            </div>

        </div>

        <ul cdkDropList class="item-dropzone" [id]="item.uId" [cdkDropListConnectedTo]="connectedDropListsIds"
            [cdkDropListData]="item" (cdkDropListDropped)="onDragDrop($event)" class="children"
            [ngClass]="{'notNested': !item.nested}">

            <ng-container *ngFor="let subItem of item.groups; let i= index">
                <div cdkDrag [ngClass]="{'expanded': item.expanded,'collapsed': !item.expanded}">
                    <div [ngClass]="{'notNestedPadding': !item.nested}">
                        <app-saved-searches-list [item]="subItem" [parentItem]="item" class="subItem"
                            [connectedDropListsIds]="allDropListsIds" (itemDrop)="onDragDrop($event)">
                        </app-saved-searches-list>
                    </div>
                </div>
            </ng-container>

        </ul>
    </div>
</div>

Error al mantener ocultos botones en Html y JavaScript [closed]

estoy intentando ocultar los botones creados dinamicamente con javascript, se ocultan al principio pero al recargar la pagina vuelven a aparecer.

document.addEventListener("DOMContentLoaded", function () {
        // Hacer una solicitud al servidor para obtener el historial al cargar la página
        fetch("/obtenerHistorial")
          .then((response) => response.json())
          .then((data) => {
            participantes = data;

            // Mostrar el historial en la pantalla
            const historialDiv = document.getElementById("historial");
            mostrarHistorial(participantes, historialDiv);

            // Crear botones después de obtener el historial
            crearBotones();
          })
          .catch((error) =>
            console.error("Error al obtener el historial:", error)
          );
        ocultarBotonSeleccionado();
      });

      function deshabilitarBotones() {
        const botones = document.querySelectorAll("button");
        botones.forEach(function (boton) {
          boton.disabled = true;
        });

        // Obtener el botón seleccionado del almacenamiento local
        const botonSeleccionadoGuardado =
          localStorage.getItem("botonSeleccionado");
        if (botonSeleccionadoGuardado) {
          // Construir la claveLocalStorage
          const claveLocalStorage = `botonSeleccionado_${botonSeleccionadoGuardado}`;

          // Obtener el valor del localStorage utilizando la nueva clave
          const botonSeleccionadoElement =
            document.getElementById(claveLocalStorage);

          // Deshabilitar el botón seleccionado si se encuentra
          if (botonSeleccionadoElement) {
            botonSeleccionadoElement.disabled = true;
            botonSeleccionadoElement.style.display = "none"; // Ocultar el botón
          }
        }
      }

      function ocultarBotonSeleccionado() {
        // Obtener el botón seleccionado del almacenamiento local
        const botonSeleccionadoGuardado =
          localStorage.getItem("botonSeleccionado");
        if (botonSeleccionadoGuardado) {
          // Construir la claveLocalStorage
          const claveLocalStorage = `botonSeleccionado_${botonSeleccionadoGuardado}`;

          // Obtener el valor del localStorage utilizando la nueva clave
          const botonSeleccionadoElement =
            document.getElementById(claveLocalStorage);

          // Ocultar el botón seleccionado si se encuentra
          if (botonSeleccionadoElement) {
            botonSeleccionadoElement.style.display = "none";
          }
        }
      }

      function crearBotones() {
        const botonesContainer = document.getElementById("botones-container");
        for (let i = 0; i < 100; i++) {
          const button = document.createElement("button");
          const numero = String(i).padStart(2, "0");
          button.id = `boton_${numero}`;
          button.textContent = numero;
          button.onclick = function () {
            // Deshabilitar botones al hacer clic
            deshabilitarBotones();
            // Ocultar el botón al hacer clic
            this.style.display = "none";
            // Llamar a la función para capturar el valor del botón seleccionado
            capturarValores(numero);
          };
          botonesContainer.appendChild(button);
        }
        ocultarBotonSeleccionado();
      }
function capturarValores(valor) {
        botonSeleccionado = valor;

        // Usar el nombre del botón como parte de la clave en localStorage
        const claveLocalStorage = `botonSeleccionado_${valor}`;

        localStorage.setItem(claveLocalStorage, valor);
      }

He probado guardando en localStorage pero no persiste el boton oculto, vuelve a aparecer cuando recargo la pagina, intente colocando un valor unico al boton, pero no se si estoy accediendo a el correctamente al recargar la pagina.

Django JWT: Keep Refresh Token Expiry Fixed on Refresh

I’m implementing JWT-based authentication for a Django website using Django Rest Framework (DRF) and Simple JWT. In my configuration, I’ve set the access token lifetime to five minutes and enabled token rotation. To handle token refreshing before expiry, I’ve implemented a JavaScript function that sends a request to refresh the access token using the refresh token. However, I’ve encountered an issue where rotating refresh tokens result in changes to their expiry dates, which prevents users from being automatically logged out when their refresh tokens expire.

Here’s the relevant JavaScript code for token refreshing:

 async function updateToken() {
    let authTokens = getTokensFromLocalStorage();
    let response = await fetch("http://127.0.0.1:8002/api/login/refresh/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ refresh: authTokens.refresh }),
    });
    let data = await response.json();
    if (response.status === 200) {
      setTokensToLocalStorage(data); // Save updated tokens to local storage
      setUser(jwtDecode(data.access)); // Update user
    } else {
      removeUser();
    }
  }

  let fourminutes = 1000 * 60 * 3; // Change to 3 minutes
  let interval = setInterval(() => {
    if (authTokens) {
      updateToken();
    } else {
      clearInterval(interval);
    }
  }, fourminutes);

And here’s a snippet of my Simple JWT settings in Django:

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
    "REFRESH_TOKEN_LIFETIME": timedelta(weeks=52),
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,
    "UPDATE_LAST_LOGIN": True,
    "ALGORITHM": "HS256",
    "SIGNING_KEY": SECRET_KEY,
    "VERIFYING_KEY": "",
    "AUDIENCE": None,
    "ISSUER": None,
    "JSON_ENCODER": None,
    "JWK_URL": None,
    "LEEWAY": 0,
    "AUTH_HEADER_TYPES": ("Bearer",),
    "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
    "USER_ID_FIELD": "id",
    "USER_ID_CLAIM": "user_id",
    "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",
    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
    "TOKEN_TYPE_CLAIM": "token_type",
    "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",
    "JTI_CLAIM": "jti",
    "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
    "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
    "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
    "TOKEN_OBTAIN_SERIALIZER": "api_key.views.MyTokenObtainPairSerializer",
    "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer",
    "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer",
    "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer",
    "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer",
    "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer",
}

Is there a way to prevent the refresh token expiry from changing upon token rotation? I want to ensure that users are logged out when their refresh tokens expire, regardless of token rotation. Any insights or suggestions on how to achieve this would be greatly appreciated

When did Chrome started to support timezone offset for Intl.DateTimeFormat()

On my Chromium 121 the following Intl.DateTimeFormat works fine:

new Intl.DateTimeFormat('en', {
      dateStyle: 'long',
      timeStyle: 'long',
      timeZone: '+0500',
    }).format(new Date());

> 'February 18, 2024 at 3:42:40 AM GMT+5'

The same on a Chrome Headless 114.0.5673.0 fails with Invalid time zone specified: +0500.

Could help me point out when/in which version this timezone format got supported ?

Next js 13.5 : After deactivating js, I no longer have html rendering

I developed my website, in next js 13.5 with app router, when I deactivate my javascript, there is no longer html rendering, which means that I have an impact on my SEO, do you have you ever faced this problem? I couldn’t find a solution :/
I also checked with screaming frog, but I don’t see my pages in the list

I made the data server side, but it doesn’t work, I did some research on the subject, but I couldn’t find any information.

GSAP text animation with mask color fails for alternate backgrounds

Greetings to everyone that’s smarter than me,

As the title states, I know just enough to be dangerous. When things get complicated, I hide in the corner, crying.

The concept: animate text on the page as the user scrolls using GSAP in Webflow. I’m using the line mask option to reveal the text. This works for all the black text on a white background using a combo class.
Example Text

The problem: I need to do the same thing for white text on a black background but I haven’t been able to accomplish this.

I’ve tried using another script and/or variables but this is where my mentor (Google) and I hit the code wall.

The website. The ABOUT ME section is what I need to get up and running.

Below is the current script and libraries.

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.1/ScrollTrigger.min.js"></script>
<script src="https://unpkg.com/split-type"></script>

<script>
gsap.registerPlugin(ScrollTrigger);

const splitTypes = document.querySelectorAll(".text-split");

splitTypes.forEach((char, i) => {
  const bg = "#F1F1F1";
  const fg = "#000000";

  const text = new SplitType(char, { types: "chars" });

  gsap.fromTo(
    text.chars,
    {
      color: bg
    },
    {
      color: fg,
      duration: 1,
      stagger: 1,
      opacity: 1,
      scrollTrigger: {
        trigger: char,
        start: "top 80%",
        end: "top 35%",
        scrub: true,
        markers: false,
        toggleActions: "play play reverse reverse"
      }
    }
  );
});
</script>

Any help would be greatly appreciated.

Thanks!

Module build failed (from ./node_modules/postcss-loader/dist/cjs.js)

I worked on this react project yesterday before pushing to git and it was running perfectly on port 3000. Got back today and I am getting this error that I am unable to resolve.

ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/index.css)
Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
SyntaxError: Unexpected token, expected “,” (22:5)
at unexpected (C:UsersADMINDesktopJAVASCRIPTJS CODESweek1.vscodeReact LibraryJojosammynode_modulessucrasedistparsertraverserutil.js:99:15)

Here is my index.css

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

body {
  background-color: #111827;
}

@font-face {
  font-family: 'NimbusSanL-Reg';
  src: url(../src/images/fonts/NimbusSanL-Reg.woff) format('woff');
}

@font-face {
  font-family: 'NimbusSanL-Bol';
  src: url(../src/images/fonts/NimbusSanL-Bol.woff) format('woff');
}

@font-face {
  font-family: 'NimbusSanL-BolIta';
  src: url(../src/images/fonts/NimbusSanL-BolIta.woff) format('woff');
}

@font-face {
  font-family: 'NimbusSanL-BolIta';
  src: url(../src/images/fonts/NimbusSanL-RegIta.woff) format('woff');
}

.name {
  font-family: 'NimbusSanL-RegIta', sans-serif;
}

.blog-header {
  font-family: 'NimbusSanL-RegIta', sans-serif;
}

My package.json below

{
  "name": "jojosammy",
  "homepage": "https://jojosammy.com/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
     "@testing-library/jest-dom": "^5.17.0",
     "@testing-library/react": "^13.4.0",
     "@testing-library/user-event": "^13.5.0",
     "babel-plugin-react-css-modules": "^5.2.6",
     "eslint": "^8.56.0",
     "react": "^18.2.0",
     "react-dom": "^18.2.0",
     "react-icons": "^5.0.1",
     "react-router-dom": "^6.22.0",
     "react-scripts": "5.0.1",
     "stylelint": "^16.2.1",
     "web-vitals": "^2.1.4"
   },
  "scripts": {
  "start": "react-scripts start",
  "predeploy": "npm run build",
  "deploy": "gh-pages -d build",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
  },
  "eslintConfig": {
  "extends": [
     "react-app",
     "react-app/jest"
   ]
  },
  "browserslist": {
  "production": [
     ">0.2%",
     "not dead",
     "not op_mini all"
   ],
   "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
   ]
 },
 "devDependencies": {
   "gh-pages": "^6.1.1",
   "tailwindcss": "^3.4.1"
}

}

getting undefined for a value when creating a jwt token in expressjs

I’m trying to create a token during the registeration of a new user :

const register = async(req, res)=>{
  const user = await User.create({...req.body})
  const token = user.createJWT()
  console.log(token); 
  
  res.status(200).json({user : {name:user.name}, token })
}

and for the createJWT method is assigned to the “methods” object of my UserSchema :

UserSchema.methods.createJWT  = function (){
  const token = jwt.sign({userId:this._id, name: this.name }, 
    process.env.JWT_SECRET,
   {expiresIn: process.env.JWT_LIFETIME})
  
  
  return  token
}

when hitting the register route and decoding the token that I got from console.log(token); I axpected a result like this :

{
  "userId": "the user id from the db",
  "name": "myName",
  "iat": 1232201499,
  "exp": 1710453499
}

but I only got :

{
  "name": "myName",
  "iat": 1232201499,
  "exp": 1710453499
}

in this reslut there I got no userId property in the payload

Google maps API not loading markers

I went got a code snippet from the Google Maps API site, and was trying to modify it to implement in my code. I am using a text search (google places) and then store each of the results in the “results” dictionary. I then implemented a loop to get the lat and long of each place to plot as markers on the map. I console log the creation of each marker, but for some reason the markers are not showing up. They are logging that each marker was created with its corresponding geographic location, just not showing up on the map. Here is my js code:

// Initialize and add the map
let map;

async function initMap() {
  const position = { lat: 39.172192, lng: -86.519409 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps", "places");
//   const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 15,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // Create a PlacesService instance
  const service = new google.maps.places.PlacesService(map);

  // Perform a text search
  service.textSearch(
    {
      query: "recycling center",
      // You can add more parameters if needed
    },
    (results, status) => {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        for (const place of results) {
            // The markers
            const marker = new google.maps.Marker({
                position: place.geometry.location,
                map: map,
                title: place.name,
            });
            marker.setVisible(true);

          console.log("Marker created: " + place.geometry.location)
          // Add a click event listener to the marker
        //   addMarkerClickListener(marker, place);
        }
      }
    }
  );
}

window.addEventListener('load', initMap);

and here is the page with my scripts loading the api:

any help would be appreciated. thanks

I tried to create a google map with markers for each location. The markers did not render

I want telegram bot answer customers instead of me

I am a seller who has many customers every day, my intention is to design a robot that when a customer tells me to send a wallet, the robot will recognize that word and send it instead of me. The point here is that I want the robot to send through my ID and the buyer is not a member of the robot
In node js it will be great tnx so much

I am a seller who has many customers every day, my intention is to design a robot that when a customer tells me to send a wallet, the robot will recognize that word and send it instead of me. The point here is that I want the robot to send through my ID and the buyer is not a member of the robotI am a seller who has many customers every day, my intention is to design a robot that when a customer tells me to send a wallet, the robot will recognize that word and send it instead of me. The point here is that I want the robot to send through my ID and the buyer is not a member of

How to persist token when user is logged in?

I have a react native web app and a user can login. But if the main page is refreshed after a user has logged in. the screen returns to the login screen.

So this is my login service:


import { removeToken, retrieveToken } from "../authentication/token";

import { API_URL } from "@env";
import AsyncStorage from "@react-native-async-storage/async-storage";

export const loginRequest = async (email, password) => {    
    const response = await fetch(`${API_URL}/api/user/token/`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            email: email,
            password: password,
        }),
    });

    const data = await response.json();

    if (response.ok) {
        await AsyncStorage.setItem("Token", data.token);

        return true;
    } else {
        throw new Error(data.token);
    }
 };
}

and login context:

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [token, setToken] = useState(AsyncStorageLib.getItem("Token"));
    const [user, setUser] = useState(null);
    const toast = useToast();

    useEffect(() => {});

    const onLogin = (email, password) => {
        setIsLoading(true);
        loginRequest(email, password)
            .then((u) => {
                setUser(u);

                setToken(u.token);
                setIsLoading(false);
            })
            .catch((e) => {
                setIsLoading(false);
                toast.show("Email of wachtwoord incorrect. Probeer het nog eens", { type: "warning" });
            });
    };

    return (
        <AuthContext.Provider
            value={{
                isAuthenticated: !!user,
                isLoading,
                error,
                user,               
                onLogin,
                
            }}>
            {children}
        </AuthContext.Provider>
    );
};

Question: how to persist token when page is refreshed?

What is wrong with my understanding of Promise in javascript that the `then` method executes functions that return Promise object, one at a time?

I try implement changing texts inside the DOM using javascript’s Promise.

<!DOCTYPE html>
<html>
<head>
    <title>js document api exercises</title>
</head>
<body>
    <script>
        const wait_thirty_sec = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('waited for 3 seconds');
                resolve('ok!!');
            }, 3000 )}
        )
        
        const insert_texts = (text) => {
            new Promise((resolve, reject) => {{
            document.body.innerHTML = `<h1>`+text+`</h1>`;
            console.log('inserted '+text+' into body'); 
            resolve('write doc!!!');
        }})
    };
            
        // insert contents into body  using javascript 
        wait_thirty_sec
       .then(() => insert_texts('Hello World!')) 
       .then(() => wait_thirty_sec) // this part fails to happen in the expected order
       .then(() => insert_texts('As from the hazy past ye rise to view;'))

    </script>
</html>

This implementation is not successful because I only can see As from the hazy past ye rise to view; displayed after about 3000ms.

This function wait_thirty_sec failed to be executed in the expected order, that is, after () => insert_texts('Hello World!'), as the console output shows

waited for 3 seconds
inserted Hello World! into body
inserted As from the hazy past ye rise to view; into body

The expected output would instead be

inserted Hello World! into body
waited for 3 seconds
inserted As from the hazy past ye rise to view; into body

I was thinking that, .then syntax just executes functions one by one.
Now this overly simplified understanding seems to be wrong. I really wish someone can explain how Promise in javascript actually works in contrary to my interpretation.

Following Second Problem Using JavaScript

So I have to create a program that takes 3 types of information from 3 prompts(hour, minute, seconds) and increments that time by 1 second. If it’s at 59 seconds it should reset to zero and increment by one minute and same with it being 59 minutes, it should increment by one hour and reset the minutes and seconds. And if it’s on the 23rd hour and both seconds and minutes are at 59, the whole time should reset to zero.

Ex: 11h29m59s should give 11h30m0s
11h59m59s should give 12h0m0s
23h59m59s should give 0h0m0s

Naturally I set up the program as if/else statements, creating conditionals that determine if the seconds, minutes, or all three reset to zero, however, it seems that the computer only reads the first conditional and ignores the following ‘else if’ statements. Is this because I don’t have the conditionals wrapped in a function? Or am I missing something in my conditionals? Did I do it all wrong? I’m not too sure, I’ve tried looking up solutions however, their solutions seem somewhat identical to what I did, so I’m kind of stumped. I feel like this is a way easier problem than what I’m making it out to be, but it felt better to ask for help than keep banging my face on the wall.

Here’s the program:

        let h = Number(prompt('Enter the hour'));
        let m = Number(prompt('Enter the minutes'));
        let s = Number(prompt('Enter the seconds'));

        if((s === 59) && (m <= 59) && (h <= 23)){
          s = 0;
          m++
           console.log(`${h}h${m}m${s}s`);
        }else if((s === 59) && (m === 59) && (h <= 23)){

           s = 0;
           m = 0;
          h++;
           console.log(`${h}h${m}m${s}s`);
        }else if((h === 23) && (m === 59) && (s === 59)){
           s = 0;
           m = 0;
           h = 0;
           console.log(`${h}h${m}m${s}s`);
        }else{
          s++;
          console.log(`${h}h${m}m${s}s`);
          }

Add filter/search to dropdown menu dynamically filled from a local json file

I’m looking for a way to add filter/search to a dropdown menu that is dynamically filled from a local json file.

Here’s my script :

var json = [{
    "id": 3,
    "name": "Ann"
  },
  {
    "id": 4,
    "name": "Karl"
  },
  {
    "id": 31,
    "name": "Jess"
  }
]

$(document).ready(function() {
  for (i in json) {
    $("#name-selector").append('<option id= "name-data" name="submit" type="submit" value="' + json[i]["name"] + '">' + json[i]["name"] + '</option>');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="div-selectors">
  <h5>Name</h5>
  <form action="" method="POST" enctype="multipart/form-data">
    <select onchange="handleData('name')" value="false" name="name" id="name-selector" class="selectors">
      <option value="">Select option</option>
    </select>
  </form>
</div>

I’ve tried to put add an input option in the dropdown menu put it places the input outside the dropdown menu.

Any idea how I could implement this ?