Push quantity value to href query string on change event

I need to update an add to cart url every time the user selects an option from 4 select elements and push a quantity value at a specific index that matches an ID. The select elements all contain the same option values and I have to create a combination of those 4 values with quantities.

Every option as a data attribute data-uid that matches a value in the query string.

How can I update the quantity value in the url and increment if the value id is selected more than once?

HTML

<div class="pick-flavor-wrapper">

    <h2>PICK 4 FLAVORS</h2>

    <select class="dropdown_1">
        <option value="none" selected disabled hidden>Select an Option</option>
        <option value="1" data-uid="689992">Thca 1</option>
        <option value="2" data-uid="689994">Thca 2</option>
        <option value="3" data-uid="690667">Thca 3</option>
        <option value="4" data-uid="690669">Thca 4</option>
    </select>
    
    <select class="dropdown_2">
        <option value="none" selected disabled hidden>Select an Option</option>
        <option value="1" data-uid="689992">Thca 1</option>
        <option value="2" data-uid="689994">Thca 2</option>
        <option value="3" data-uid="690667">Thca 3</option>
        <option value="4" data-uid="690669">Thca 4</option>
    </select>
    
    <select class="dropdown_3">
        <option value="none" selected disabled hidden>Select an Option</option>
        <option value="1" data-uid="689992">Thca 1</option>
        <option value="2" data-uid="689994">Thca 2</option>
        <option value="3" data-uid="690667">Thca 3</option>
        <option value="4" data-uid="690669">Thca 4</option>
    </select>
    
    <select class="dropdown_4">
        <option value="none" selected disabled hidden>Select an Option</option>
        <option value="1" data-uid="689992">Thca 1</option>
        <option value="2" data-uid="689994">Thca 2</option>
        <option value="3" data-uid="690667">Thca 3</option>
        <option value="4" data-uid="690669">Thca 4</option>
    </select>

</div>

<a class="add_to_cart_grouped" href="https://example.com/?add-to-cart=689991&quantity[689992]=0&quantity[689994]=0&quantity[690667]=0&quantity[690669]=0">Add to cart</a>

Javascript

    // Get product ID
    document.querySelectorAll("select").forEach(dropdown => {
            let prodID;
        
            dropdown.addEventListener("change", () => {
               let selectedOptionID = dropdown.selectedIndex;
               prodID = dropdown.options[selectedOptionID].dataset.uid;
               updateURL(prodID);
            })
    })
    
    function updateURL(prodID) {
        let href = document.querySelector(".add_to_cart_grouped").getAttribute("href");
        let urlIndex = href.indexOf(prodID);
        let arr = [...href];         
        arr.splice(urlIndex + 8, 1, "1");
        href = arr.join("");
        console.log(href)
    }

I tried writing a function that fires when selecting an option and it updates the url at a specific index using the splice method, but it doesn’t save the previous value in the href.

how to detect when a gif has played once using javascript?

i was wondering if it was possible to detect when a gif has reached its loop point using javascript, to emulate the preloaders of flash content
currently, i have a script to detect when the video is loaded that runs every few frames (taken from here). i was wondering if there was a way to run this every time the gif has ended? i would prefer to not use timeouts if possible, due to wanting to reuse code.

right now, the video is automatically played when it has finished loading, no matter where the gif is

current javascript:

 const videoElement = document.getElementById('video');
 const preloader = document.getElementById('preloader');

 videoElement.addEventListener('loadeddata', (e) => {
 //Video should now be loaded but we can add a second check

 if(videoElement.readyState >= 3){
     console.log("video's done loading");
     preloader.style.display = 'none'
 }

 });

example

I can’t figure out which bugs are ruining my JavaScript?

I’m trying to create my first webpage using HTML, CSS, and JavaScript. I understand the basics of HTML/CSS but JavaScript is a doozy.

Here is the scenario: I’m creating a pizza order form. The final product needs to look something like this and right now my product looks like this (Ignore the specific CSS elements for this post; I’m having trouble with JS).

Comparing both models, the text in the input fields are missing, along with the arrays underneath “Completed Pizza Order” and the “Sales Total”. There are likely several errors in my code, however the only error the console is giving me is this. Below you’ll find the essential part the HTML I’m working with, to help you crosscheck what JavaScript is trying to fetch. For JS, you’ll find the //instructions along with the code I gave my best shot at. I would greatly appreciate it if you could add any pointers to what’s wrong with my JS.

  • HTML
        <div>
            <form>
                <label for="crust">Choose Your Crust:</label>
                <input type="text" id="pizzaCrust"/><br>
                <label for="sauce">Choose Your Sauce:</label>
                <input type="text" id="pizzaSauce"/><br> 
                <label for="firstTopping">Topping 1:</label>
                <input type="text" id="firstTopping"/>
                <label for="secondTopping">Topping 2:</label>
                <input type="text" id="secondTopping"/>
                <label for="thirdTopping">Topping 3:</label>
                <input type="text" id="thirdTopping"/><br>
                <button name="submit" type="submit" id="btn">Create Order</button>
            </form>
        </div>
        <div id="order">
            <p>Completed Pizza Order:</p>
            <div id="pizzaOrder"></div>
            <div id="toppings"></div>
            <p>Sales Total:</p>
            <div id="total">$</div>
        </div>
        <script src="script.js"></script>
    </body>
  • JAVASCRIPT
// Add global variables 

var crust = "pizzaCrust";
var sauce = "pizzaSauce";

// Add toppings array

var toppings = []
console.log(toppings.length);


// Add event listener

var formButton = document.getElementByID('btn');
btn.addEventListener("click", function(event){
    event.preventDefault();
}) 

// - Create three variables named topping1, topping2, and topping3. 
// - Set those variables equal to the DOM element they correspond with, using the ids you created in the index.html file. 
// - Each variable should hold the value of its corresponding form input.
// - Push the three topping variables into the empty toppings array.

var topping1 = document.getElementById('firstTopping').value;
    toppings.push("topping1");
var topping2 = document.getElementById('secondTopping').value;
    toppings.push("topping2");
var topping3 = document.getElementById('thirdTopping').value;
    toppings.push("topping3"); 

// - Call the calculateTotal() function below, and pass it the toppings array as a parameter.

toppings.push(calculateTotal);

// Code that was originally provided

function calculateTotal(toppingArray) {  
    let total = 0; 
    let toppingCost = 2.50; 
    let baseCost = 5.50; // cost of crust and sauce
    
// - Create a variable called orderString using the let keyword, and set it to a string containing the base parts of the pizza. 

    let orderString = (crust + "pizza with " + sauce);

// Code that was originally provided

    let toppingString = "Toppings: ";

// - Use a for loop to loop through the entire length of he toppingArray parameter.
// - Update the total variable to add toppingCost to itself.
// - Set toppingString equal to toppingString plus the value within toppingArray at its current index position, concatenated with a string of empty space " ".
// - Create a single if statement that verifies that each topping was filled out before adding the topping to the toppingString and before increasing the total.

    for (i=0; i < toppingArray.length; i++)
        total += toppingCost[i];
        toppingString += toppingArray[i] + " ";
    if (toppings) {
        toppingString += topping + " ";
        total++; 
    }

// Add the baseCost to the existing total by setting total equal to total plus baseCost.

    total += baseCost


// Use innerHTML to post the total variable to the element that has the id of total.

document.getElementById("total").innerHTML = total;

// Use innerHTML to post the orderString variable to the element that has the id of pizzaOrder.

document.getElementById("pizzaOrder").innerHTML = orderString;
 
// Use innerHTML to post the toppingString variable to the element that has the id of toppings.

document.getElementById("toppingString").innerHTML = toppingString;
 
}

how to change background image of a polygon in amcharts5?

I am creating an interactive map using amCharts5 in JS and I want to replace a certain country, like Canada for example with an image from the place I’ve been in Canada and the image must have the shape of the country

I tried fill: am5.color.pattern("images/canada.jpg") but it’s not working


  // Create root and chart
  const root = am5.Root.new("chartdiv");

  // Set themes
  root.setThemes([am5themes_Animated.new(root)]);

  const chart = root.container.children.push(
    am5map.MapChart.new(root, {
      panX: "rotateX",
      projection: am5map.geoNaturalEarth1(),
    })
  );

  // Create polygon series
  const polygonSeries = chart.series.push(
    am5map.MapPolygonSeries.new(root, {
      geoJSON: am5geodata_worldLow,
      exclude: ["AQ"],
    })
  );

  polygonSeries.mapPolygons.template.setAll({
    tooltipText: "{name}",
    templateField: "polygonSettings",
  });

  polygonSeries.mapPolygons.template.states.create("hover", {
    fill: am5.color(0x677935),
  });

  polygonSeries.data.setAll([
    {
      id: "US",
      polygonSettings: {
        fill: am5.color(0xff3c38),
      },
    },
    {
      id: "CA",
      polygonSettings: {
        fill: am5.color.pattern("images/canada.jpg"),//This is not working
      },
    },
    {
      id: "MX",
      polygonSettings: {
        fill: am5.color(0xff8c42),
      },
    },
  ]);
});

Dynamic server usage: Page couldn’t be rendered statically because it used `nextUrl.searchParams` in Next.js version 14

I am in very critical trouble, let me explain

I am creating a full stack application with next js 13,
I have created an API that is perfectly working in dev(npm run dev) mode but the problem is when I give the build command(npm run build) then it shows the flowing error.
Please anybody bring me out of the problem.
Error Screenshot – https://prnt.sc/VaN1wHifqK_2

 [Error]: Dynamic server usage: Page couldn't be rendered statically because it used `nextUrl.searchParams`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error

Here is my code.
This is the API function for getting users from the database using url searchParams

// /backend/apiControllers/getUsers.js

import prisma from "@/prisma/prismaClient";

export const getUsers = async (request) => {
  const { nextUrl } = request; // here is the problem, this is working for dev mode but not in production build mode.
  const email = nextUrl.searchParams.get("email") || "";
  const phone = nextUrl.searchParams.get("phone") || "";
  const id = nextUrl.searchParams.get("id") || "";

  let queryParam = {};

  if (email) {
    queryParam = {
      where: {
        ...queryParam.where,
        email: {
          equals: email,
          mode: "insensitive",
        },
      },
    };
  }
  if (phone) {
    queryParam = {
      where: {
        ...queryParam.where,
        phone: {
          equals: phone,
        },
      },
    };
  }
  if (id) {
    queryParam = {
      where: {
        ...queryParam.where,
        id: {
          equals: id,
        },
      },
    };
  }

  try {
    const users = await prisma.users.findMany(queryParam);
    return users;
  } catch (error) {
    return { apiMessage: { errorMsg: "Unable to find User details" } };
  }
};

And I have called that function into /app/api/armies/route.js

// /app/api/armies/route.js

import { getUsers } from "@/backend/apiControllers/getUsers";
import { connectDB } from "@/backend/utils/dbConnect";
import { NextResponse } from "next/server";

export const GET = async (request) => {
  try {
    await connectDB();
    const users = await getUsers(request); //called here
    return NextResponse.json(users);
  } catch (error) {
    console.log(error);
    return NextResponse.json({
      apiMessage: { errorMsg: "Internal Server Error, Please try again later" },
    });
  }
};

I have tried the following method also “const url = new URL(request.url);” but the same error, Here is the error screenshot – https://prnt.sc/Z3D317lDQ3CP

import prisma from "@/prisma/prismaClient";

export const getUsers = async (request) => {
  const url = new URL(request.url); // here is the problem, this is working for dev mode but not in production build mode.
  const email = url.searchParams.get("email") || "";
  const phone = url.searchParams.get("phone") || "";
  const id = url.searchParams.get("id") || "";

  let queryParam = {};

  if (email) {
    queryParam = {
      where: {
        ...queryParam.where,
        email: {
          equals: email,
          mode: "insensitive",
        },
      },
    };
  }
  if (phone) {
    queryParam = {
      where: {
        ...queryParam.where,
        phone: {
          equals: phone,
        },
      },
    };
  }
  if (id) {
    queryParam = {
      where: {
        ...queryParam.where,
        id: {
          equals: id,
        },
      },
    };
  }

  try {
    const users = await prisma.users.findMany(queryParam);
    return users;
  } catch (error) {
    return { apiMessage: { errorMsg: "Unable to find User details" } };
  }
};

But again the same error

How to Correctly Integrate SwiperJS into an Astro Component to Avoid Module Resolver Errors?

I’m working on a project using Astro and trying to integrate SwiperJS. Everything works as expected locally, but as soon as I deploy my application to the server, issues arise. Specifically, I encounter an error when attempting to import SwiperJS through a tag in my .astro file. The error I receive is:

Uncaught TypeError: Failed to resolve module specifier "@swiper/swiper-bundle.min.mjs". Relative references must start with either "/", "./", or "../".

Here’s a snippet of my code showing how I’m trying to integrate SwiperJS:

<script type="module">
    import Swiper from '@swiper/swiper-bundle.min.mjs';
    // Initialize Swiper...
</script>

I have tried various methods to fix this error, including changing the import path to relative and absolute paths, but I still get similar error messages.

Questions:

How can I integrate SwiperJS into an Astro component without encountering module resolver errors, especially when deploying to a server?
Is there a specific way import paths should be handled in Astro to avoid such issues?
Has anyone experienced something similar and found a solution that works both locally and on the server?
I followed the guide for integrating SwiperJS into Astro, but this specific issue does not seem to be directly addressed in the documentation or common guides. Any help or advice on how to resolve this import error would be greatly appreciated.

Transparent PNG Image Copied to Clipboard Renders with Black Background

I’m encountering an issue with a JavaScript function in a web application. The function copies a PNG image (rendered using LaTeX and Matplotlib in a Django backend) to the clipboard. When downloaded, the image maintains its transparency as expected. However, when copied to the clipboard using JavaScript, the transparent background turns black.

Here’s a simplified version of the JavaScript code responsible for copying the image:

document.getElementById('copyButton').addEventListener('click', function() {
    var imgElement = document.getElementById('renderedImage');
    if (imgElement) {
        var canvas = document.createElement('canvas');
        canvas.width = imgElement.naturalWidth;
        canvas.height = imgElement.naturalHeight;
        var ctx = canvas.getContext('2d');
        ctx.globalCompositeOperation = 'copy';
        ctx.drawImage(imgElement, 0, 0);
        canvas.toBlob(function(blob) {
            var clipboardItem = new ClipboardItem({'image/png': blob});
            navigator.clipboard.write([clipboardItem]);
        }, 'image/png');
    }
});

The issue seems to occur across multiple browsers. I suspect it might be related to how the canvas or the clipboard API handles the image data, particularly the transparency. However, on Firefox this actually appears to be unsupported completely.

Could anyone provide insights or solutions on how to maintain the transparency of the PNG image when copying it to the clipboard? I do not mind using a different method completely.

What I tried:
Checked and confirmed that the original image has transparency.
Set globalCompositeOperation to ‘copy’ to preserve transparency.
Tested in multiple browsers (issue persists across Chrome and Edge, while Firefox doesn’t support ClipboardItem yet).

What I was expecting:
When users copy the image to the clipboard, I expect the transparency to be preserved, just as it is when the image is downloaded.

Question:
How can I ensure that the transparency of copied images is preserved when using the Clipboard API? Is there a specific method or workaround to prevent the transparent background from turning black in the clipboard?

RangeError: Array buffer allocation failed using JSZip

I’m working on an application that allows users to download images related to a project. Each project has several different images relating to them. On my application I have a button that allows users to specify an ID for a project and then download all the images for that project.
I’m using JSZip to zip all the images and then download it to the users browser.

This implementation is working so far, but when the user tries to download images for a project that contains a lot images, once zip.generateAsync is called, the application crashes and returns the error:

RangeError: Array buffer allocation failed

I’m assuming this is because the size of the zip to be generated is too large which causes the crash. What can I do to navigate around this error as the user still needs to be able to access all the images?

        //Iterate through all files found
        for (let i = 0; i < filesArr.length; i += 2) {
            zip.file(filesArr[i], filesArr[i + 1], { base64: true });
            await timers.setTimeout(100);
        }

        console.log('files zipped')
        let z = await zip.generateAsync({ type: "nodebuffer" })
        //code is not making it past zip.generateAsync() when there are too many results
        console.log('zip generated')
        filesArr = [];
        return res.send(z)

Wrong behaviour with Mui v4 textfield and string validation

I am trying to make a validation on a mui text field

<TextField
                        name={`persona/${deiValue._id}/${data.indicator}`}
                        value={deiValue.value || ''}
                        variant="outlined"
                        placeholder="Add"
                        disabled={mode.value !== LAYOUT_CONSTANTS.MODE.EDIT.value}
                        inputProps={{
                          'aria-label': 'persona'
                        }}
                        InputProps={{
                          classes: {
                            input: classes.inputStyles
                          },
                          endAdornment: (
                            <InputAdornment position="end" disableTypography={true}>
                              <Typography variant="body2">%</Typography>
                            </InputAdornment>
                          )
                        }}
                        onChange={e => this.handleInputChange(e, deiValue._id)}
                        onInput={e => {
                          if (!validateNumberFieldWDecimals(e.target.value)) {
                            console.log("false")
                            e.target.value = e.target.value.substring(0, e.target.value.length - 1);
                          }
                        }}
                      />

And the i have the validateNumberFieldWDecimals I run onInput, also tried logging all the values, (“22.” === input) gives true, both have type of string even tried to copy it with a string template but the regex keeps giving false when I add the first decimal

  const stringInput = `${input}`
  if (input === "") return true;
  const regex = /^(?!.*e)(d{1,2}(.d{1,2})?|100(.0{1,2})?)$/;
  const result = regex.test(stringInput)
  console.log("22.");
  console.log(stringInput);
  console.log("22." === input);
  console.log(regex.test("22.2"), 'hand');
  console.log(regex.test(stringInput), 'inputvalue');
  return result;
}

Django Rest: On axios post for user_id key, null is always returned, even with a value for user_id sent

enter image description here
enter image description here

I send over the value for user_id, it receives it and then returns it always as null. It is posting to a foreignkey, just not entirely sure what i am missing here.

Post

 const article = {
        "deck_name": deck_name.value,
        "deck_type": deck_type.value,
        "user_id": user_id,
    }
    var CSRF_TOKEN = "{{csrf_token}}"
    console.log(user_id.value)
    headers = {
        headers: {
        'X-CSRFToken': CSRF_TOKEN,
        }
    }
      response = axios.post('http://localhost:8000/rest/decks/', article, headers)
      console.log(response.status_code, response.content)

Seriliazer

class Deck(serializers.ModelSerializer):

    class Meta:
        model = Decks
        fields = (
            "deck_name",
            "deck_id",
            "deck_colors",
            "image_small",
            "deck_type",
            "user_id"
        )

Model

class Decks(models.Model):
    deck_id = models.AutoField(primary_key=True)
    deck_type = models.CharField(max_length=255, default="Standard")
    deck_colors = models.CharField(max_length=100, default="r")
    deck_name = models.CharField(max_length=255)
    image_small = models.CharField(max_length=255, default='https://i.pinimg.com/564x/c3/f2/45/c3f245bdfa2ecc879530b205d8c1f972.jpg')
    user = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE)

Drizzle ORM issue with count and filtering

There has to be better way to do this right? There must be a way to have 1 base query and then one returns values other one returns count

This does work, but it requires to duplicate all of the filtering for each query

const drizzle = await db();

// Base query for fetching rows with filters applied
let rowsQuery: any = drizzle
  .select()
  .from(verTable)
  .orderBy(verTable.id)
  .limit(limit)
  .offset(offset);

// Base query for counting total rows with same filters
let totalQuery: any = drizzle.select({ value: count() }).from(verTable);

// Apply filters to both queries
if (title) {
  rowsQuery = rowsQuery.where(ilike(verTable.title, `%${title}%`));
  totalQuery = totalQuery.where(ilike(verTable.title, `%${title}%`));
}
if (industryDesc) {
  rowsQuery = rowsQuery.where(
    or(
      ilike(verTable.industry, `%${industryDesc}%`),
      ilike(verTable.desc, `%${industryDesc}%`)
    )
  );
  totalQuery = totalQuery.where(
    or(
      ilike(verTable.industry, `%${industryDesc}%`),
      ilike(verTable.desc, `%${industryDesc}%`)
    )
  );
}
if (state) {
  rowsQuery = rowsQuery.where(ilike(verTable.state, `%${state}%`));
  totalQuery = totalQuery.where(ilike(verTable.state, `%${state}%`));
}
if (company) {
  rowsQuery = rowsQuery.where(ilike(verTable.company_name, `%${company}%`));
  totalQuery = totalQuery.where(
    ilike(verTable.company_name, `%${company}%`)
  );
}

// Execute the queries
const rows = await rowsQuery;
const total = await totalQuery;

check if radio button is clicked to navigate to another page in react native

I am very new to react native. I want someone to edit the following code to add a
three radio buttons and a button, when I click on this button, check which radio
button is clicked to navigate to one of the screens in the code. if radio button one
is clicked go to screen one ,if radio button 2 is selected go to screen two
and so on. I am good at javascript and I know react native is based on javascript, so
I guess you will advice me to use switch command, but I do not know ho use switch in
react native. I followed some tutorial but the code I used produced error like
“navigation does not exist” after I managed to set the development environment correctly
please, please , please help`, also do you recommend me
some books that explain react native in detail, thank you very much

     here is my code


























        






     // I guess Switch will be used, but I do not know how






import React from 'react';
    import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';


    import {NavigationContainer} from '@react-navigation/native';
    import {createStackNavigator} from '@react-navigation/stack';

   //Screen One.
  const ScreenOne = props => {


  const onPress = () => {
  props.navigation.navigate('ScreenTwo');
  };

     return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
    <TouchableOpacity onPress={onPress}>
    <Text>Hello From Screen One</Text>
    </TouchableOpacity>
    </View>
    );
    };


  //Screen Two. 
   const ScreenTwo = () => {
   return (
   <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
  <Text>Screen Two</Text>
  </View>
  );
  };


   //Screen Three. 
   const ScreenThree = () => {
   return (
   <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
   <Text>Screen Three</Text>
   </View>
   );
   };


   const App = () => {

   const Stack = createStackNavigator();

   return (
   <NavigationContainer>
   <Stack.Navigator>
   <Stack.Screen name="ScreenOne" component={ScreenOne} />
   <Stack.Screen name="ScreenTwo" component={ScreenTwo} />
    <Stack.Screen name="ScreenThree" component={ScreenThree} />
    </Stack.Navigator>
    </NavigationContainer>
    );
    };

    export default App;

Como puedo comprobar si las letras de la selecion coincide letra del alfabeto

Hola tengo un codigo javascript que es para crear un juego de palabras. tengo la frase oculta que muestra algunas letras aleatorio con su numero, y tengo un alfabeto para poder pulsar, primero seleciono la letra de la frase y luego deberia de pulsar una letra del alfabeto y si coincide que muestre la letra oculta de la frase pero no me funcion, me creado un alert y el alert dice que la selecion de la frase es por ejemplo la “A” si si pulso la “A” de alfabeto dice que es la “A” pero dice que no coinciden. adjunto codigo

<script>
$(document).ready(function() {
  var frase = "El que sonríe gana"; // Cambia la frase aquí
  var box_text = $("#box_text");
  var letraSeleccionada = null; // Variable para almacenar la letra seleccionada

  var letrasPorRevelar = []; // Array para almacenar las letras únicas que se revelarán

  // Iterar sobre cada letra de la frase
  for (var i = 0; i < frase.length; i++) {
    var letra = frase[i].toUpperCase();

    // Verificar si la letra ya está en el array de letras por revelar
    if (!letrasPorRevelar.includes(letra) && letra !== " ") {
      letrasPorRevelar.push(letra); // Agregar la letra al array de letras por revelar
    }
  }

  // Calcular el número de letras a revelar basado en el 25% de la longitud total de la frase
  var letrasARevelar = Math.round(letrasPorRevelar.length * 0.5); 

  // Elegir aleatoriamente las letras que se van a revelar
  var letrasReveladas = [];
  while (letrasReveladas.length < letrasARevelar && letrasPorRevelar.length > 0) {
    var indice = Math.floor(Math.random() * letrasPorRevelar.length); // Seleccionar un índice aleatorio
    var letraSeleccionada = letrasPorRevelar.splice(indice, 1)[0]; // Quitar la letra seleccionada del array y obtenerla

    letrasReveladas.push(letraSeleccionada); // Agregar la letra seleccionada al array de letras reveladas
  }

  // Objeto para almacenar los números asignados a cada letra
  var numerosAsignados = {};

  // Función para generar un número aleatorio único
  function generarNumeroUnico() {
    var numero;
    do {
      numero = Math.floor(Math.random() * 31); // Genera un número aleatorio entre 0 y 30
    } while (Object.values(numerosAsignados).includes(numero)); // Verifica si el número ya está asignado a otra letra
    return numero;
  }

  // Función para verificar si una letra coincide con una selección de texto
  function verificarCoincidencia(letra, texto) {
    // Convertir el texto y la letra a minúsculas para hacer la comparación insensible a mayúsculas y minúsculas
    texto = texto.toLowerCase();
    letra = letra.toLowerCase();

    // Verificar si la letra está presente en el texto
    if (texto.includes(letra)) {
      return true;
    } else {
      return false;
    }
  }

  // Mostrar las letras en el cuadro de texto
  var palabraActual = $("<div>").addClass("box_cuvant");
  for (var i = 0; i < frase.length; i++) {
    var letra = frase[i].toUpperCase();
    var litera;
    if (letra === " ") { // Si es un espacio, agregamos una nueva palabra al texto
      box_text.append(palabraActual);
      box_text.append(" ");
      palabraActual = $("<div>").addClass("box_cuvant"); // Reiniciamos la palabra actual
    } else {
      var numero = letra in numerosAsignados ? numerosAsignados[letra] : generarNumeroUnico();
      var litera_alfabet = $("<div>").addClass("litera_alfabet").text(letrasReveladas.includes(letra) ? letra : "");
      var separacion = $("<div>").addClass("separacion");
      var litera_numar = $("<div>").addClass("litera_numar").text(numero);

      litera = $("<div>").addClass("litera").addClass("litera_alfabet").attr("data-letra", letra).append(litera_alfabet, separacion, litera_numar);
      palabraActual.append(litera);
      letrasReveladas = letrasReveladas.filter(function(l) { return l !== letra; }); // Remover la letra revelada del array
      numerosAsignados[letra] = numero; // Asignar el número a la letra
    }
  }
  box_text.append(palabraActual); // Agregamos la última palabra

  // Manejar el clic en las letras del alfabeto
  $("#alfabeto").on("click", ".letra_alphabet", function() {
    var letraClicada = $(this).text().toUpperCase(); // Obtener la letra clicada en el alfabeto en mayúsculas

    // Verificar si hay una letra oculta seleccionada en el cuadro de texto
    if (letraSeleccionada !== null) {
      // Verificar si la letra clicada del alfabeto coincide con la letra seleccionada en el cuadro de texto
      if (letrasReveladas.includes(letraClicada) && letraClicada === letraSeleccionada) {
        // Mostrar un alert si la letra del alfabeto coincide con la letra oculta seleccionada
        alert("La letra seleccionada de la frase es '" + letraSeleccionada + "' y coincide con la letra '" + letraClicada + "' del alfabeto.");
      } else {
        // Mostrar un alert si la letra del alfabeto no coincide con la letra oculta seleccionada
        alert("La letra seleccionada de la frase es '" + letraSeleccionada + "' y no coincide con la letra '" + letraClicada + "' del alfabeto.");
      }
    }
  });

  // Manejar el clic en las letras del texto oculto
  $(".litera_alfabet").click(function() {
    // Obtener la letra clicada
    var letraClicada = $(this).text();

    // Guardar la letra seleccionada
    letraSeleccionada = letraClicada;

    // Remover la selección de todas las letras
    $(".litera_alfabet").removeClass("seleccionado");

    // Remover la selección de los números
    $(".litera_numar").removeClass("seleccionado");

    // Seleccionar la letra clicada
    $(this).addClass("seleccionado");

    // Seleccionar el número correspondiente
    $(this).siblings(".litera_numar").addClass("seleccionado");

    // Verificar si hay una letra oculta seleccionada en el cuadro de texto
    if (letraSeleccionada !== null) {
      // Obtener el número asociado a la letra seleccionada
      var numeroAsociado = $(this).siblings(".litera_numar").text();

      // Mostrar un mensaje con la letra y su número correspondiente
      console.log("La letra seleccionada es: " + letraSeleccionada + " - Número: " + numeroAsociado);

      // Verificar si la letra seleccionada coincide con la letra de la frase
      var textoFrase = frase.replace(/s/g, ''); // Eliminar espacios en blanco de la frase
      if (verificarCoincidencia(letraSeleccionada, textoFrase)) {
        console.log('La letra seleccionada coincide con una letra de la frase.');
      } else {
        console.log('La letra seleccionada no coincide con ninguna letra de la frase.');
      }
    }
  });

  // Manejar el clic en las letras de la frase
  $(".litera").click(function() {
    var letraClicada = $(this).find('.litera_alfabet').text(); // Obtener la letra clicada
    var numeroAsociado = $(this).find('.litera_numar').text(); // Obtener el número asociado

    // Obtener la letra asociada al número
    var letraAsociada = letraClicada.trim() !== '' ? letraClicada : Object.keys(numerosAsignados).find(key => numerosAsignados[key] === parseInt(numeroAsociado));

    // Mostrar un mensaje con la letra y su número correspondiente
    console.log("La letra seleccionada es: " + letraAsociada + " - Número: " + numeroAsociado);
  });

  // Generar dinámicamente las letras del alfabeto
  for (var i = 65; i <= 90; i++) {
    var letra = String.fromCharCode(i); // Convertir el código ASCII en letra
    var letraEnLinea = $("<div>").addClass("letra_alphabet").text(letra); // Crear el elemento div con la letra y agregar la clase correspondiente
    $("#alfabeto").append(letraEnLinea); // Agregar la letra al div "alfabeto"
  }
});

</script>

Updating email attribute in aws cognito through aws amplify is not working propertly

I have a react native project that has AWS cognito and AWS amplify integrated into it. Right now, I am trying to setup a feature where a user can update their email. Once the submit the new email, they will be shown a screen to confirm the new email with an emailed confirmation code. Once the confirmation code is set, the email show be verified in aws cognito and I will then update the email in AWS RDS database. For some reason, when the user types in the new email. A confirmation code is sent to the new email which is working. Then when I go into AWS cognito and AWS amplify, the new email is not set and the new email is not set to unconfirmed. Not sure how it is send a new confirmation email, but in aws cognito, the new email does not show up.

Here is my functions for updating the email and confirming the code:

const updateEmailForCode = () => {
    updateUserAttributes({
      userAttributes: {
        email: email
      }
    })
    .then((response) => {
      setViewEmail(false)
    })
    .catch((err) => {
      console.log(err)
    })
  }

  const confirmUpdateEmail = () => {
    confirmSignUp({
      username: user.username,
      confirmationCode: emailCode
    })
    .then(response => {
      console.log(response)
      setEditProfile(!editProfile)
    })
    .catch(error => {
        console.log('Error confirming sign up', error);
    });
  }

Here is what the existing email is:

[email protected]

Here is the new temporary email I want to update:

[email protected]

I submitted the new email and got the new verification email:

picture of email verification

I then get the following error:

 LOG  Error confirming sign up [NotAuthorizedException: User cannot be confirmed. Current status is CONFIRMED]

When I go into amazon cognito, it shows the old email and that it is confirmed rather than the new email:

email confirmed

I dont know why the new email is not showing up as the email and status of unconfirmed… Can anyone help me figure out why this is happening.

Here is my entire component:

import React, { useContext, useState } from 'react'
import { SafeAreaView, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native'
import { Plus, RefreshCcw, X } from 'react-native-feather'
import InputFieldComponent from '../General/InputFieldComponent'
import { UserContext } from '../../Context/UserContext'
import MainButton from '../General/MainButton'
import { confirmSignIn, confirmSignUp, updateUserAttribute, updateUserAttributes } from 'aws-amplify/auth'


const EditEmailProfileComponent = (props) => {
  const { setEditProfile, editProfile } = props

  const {profile, user, getUserProfile} = useContext(UserContext)

  const [email, setEmail] = useState(profile.email)
  const [emailCode, setEmailCode] = useState('')

  const [viewEmail, setViewEmail] = useState(true)

  const updateEmail = (text: string) => {
    setEmail(text)
  }

  const updateCode = (text: string) => {
    setEmailCode(text)
  }

  const updateEmailForCode = () => {
    updateUserAttributes({
      userAttributes: {
        email: email
      }
    })
    .then((response) => {
      setViewEmail(false)
    })
    .catch((err) => {
      console.log(err)
    })
  }

  const confirmUpdateEmail = () => {
    confirmSignUp({
      username: user.username,
      confirmationCode: emailCode
    })
    .then(response => {
      console.log(response)
      setEditProfile(!editProfile)
    })
    .catch(error => {
        console.log('Error confirming sign up', error);
    });
  }

  return (
    <SafeAreaView style={styles.container}>
      {
        viewEmail
          ? <View style={styles.content}>
              <View style={styles.header}>
                <Text style={styles.headerText}>Update Email</Text>
                <TouchableOpacity onPress={() => {setEditProfile(!editProfile)}} >
                  <X height={26} width={26} color={'#e94f4e'}/>
                </TouchableOpacity>
              </View>
              <InputFieldComponent 
                palceholder='First Name'
                label='User'
                value={email}
                handleFunction={updateEmail}
                secure={false}
                validation={true}
              />
              <MainButton label={'Update Email'} handleFunction={() => {updateEmailForCode()}}/>
            </View>
          : <View style={styles.content}>
              <View style={styles.header}>
                <Text style={styles.headerText}>Confirm Code</Text>
                <TouchableOpacity onPress={() => {setEditProfile(!editProfile)}} >
                  <X height={26} width={26} color={'#e94f4e'}/>
                </TouchableOpacity>
              </View>
              <InputFieldComponent 
                palceholder='Confirmation Code'
                label='User'
                value={emailCode}
                handleFunction={updateCode}
                secure={false}
                validation={true}
              />
              <MainButton label={'Confirm Code'} handleFunction={() => {confirmUpdateEmail()}}/>
            </View>
      }
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0,0,0,0'
  },
  content: {
    width: '100%',
    backgroundColor: 'white',
    paddingVertical: 25,
    display: 'flex',
    flexDirection: 'column',
    paddingHorizontal: 16,
    borderRadius: 32
  },
  header: {
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  headerText: {
    fontSize: 24,
    fontWeight: 'bold'
  },
  pictureText: {
    fontSize: 20,
    fontWeight: 'bold',
    marginTop: 16
  },
  placeHolder: {
    height: 125,
    width: 125,
    backgroundColor: 'lightgrey',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 16,
    marginTop: 8
  },
  image: {
    height: 125,
    width: 125,
    borderRadius: 16,
    marginTop: 8
  },
  imageIcon: {
    height: 18,
    width: 18,
    color: '#e93f3e',
    margin: 10,
    marginLeft: 14
  },
  menuOptions: {
    display: 'flex',
    flexDirection: 'row'
  }
})

export default EditEmailProfileComponent

How to find which DOM element corresponds to precise scroll position

I need to find the DOM element that corresponds to my horizontal scolling position. Passing a position of 25px should return the DOM element #2.

So far what I did is calculating the width of my elements to find the one that corresponds to the scrolling position but this is not a viable solution since in my real application my element’s widths are not equal. Asking here if there is a more logical way of doing this.

pass a position of 25px the DOM element 2 is returned

I am using Vue js but it’s not a requierement for the solution to my problem.