Skip to main content

How can I select multiple items that are generated in real time with JS?

I'm trying to get the user preferences, which will be 5 or 10, I haven't defined that yet.

But the options that will be shown in the first instance are the following (They are being retrieved in a JSON through a WebApi, but for example, I put what I get):

<?php
    $json2 = '{"0":{"Id_Categoria":2,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631725779\/neb2ymglgqmmaexgkcez.png","Nombre":"Vinos y licores","Activo":1,"demanda":148},"1":{"Id_Categoria":1,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631725152\/umk40bjvcxpoc08bcu7q.png","Nombre":"Calzado","Activo":1,"demanda":52},"2":{"Id_Categoria":21,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726499\/ciperp26mazrm7wao9fs.png","Nombre":"Carnicerias","Activo":1,"demanda":9},"3":{"Id_Categoria":22,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726499\/ciperp26mazrm7wao9fs.png","Nombre":"Cafeterias","Activo":1,"demanda":7},"4":{"Id_Categoria":25,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726499\/ciperp26mazrm7wao9fs.png","Nombre":"Taquerias","Activo":1,"demanda":7},"5":{"Id_Categoria":3,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631725966\/q5cczltjedz1wg1iat8f.jpg","Nombre":"Articulos (c\u00f3mputo)","Activo":1,"demanda":6},"6":{"Id_Categoria":24,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726499\/ciperp26mazrm7wao9fs.png","Nombre":"Tintorerias","Activo":1,"demanda":6},"7":{"Id_Categoria":4,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726499\/ciperp26mazrm7wao9fs.png","Nombre":"Paletass y helados","Activo":1,"demanda":5},"8":{"Id_Categoria":5,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726157\/qad9inm54ma56s2s4tta.png","Nombre":"Comercios de Pintura","Activo":1,"demanda":5},"9":{"Id_Categoria":23,"Imagen":"https:\/\/res.cloudinary.com\/dcksq4ylu\/image\/upload\/v1631726499\/ciperp26mazrm7wao9fs.png","Nombre":"Ferreterias","Activo":1,"demanda":4}}';
    
    echo($json2);
?>

I am retrieving this JSON with ajax in the following way (I think it is the simplest):

$("#Abrir").click(function() {
        //$(document).ready(function(){
        //invocar json desde jquery
        $("#Class2 div").remove();
        $.ajax({
            url: "prueba.php",
            //Datos que se envian a prueba.php
            data: {},
            //Cambiar a type: POST si necesario
            type: "GET",
            // Formato de datos que se espera en la respuesta
            dataType: "json",
            success: function(datos) {
                //Información que llega
                var salida = "";
                $.each(datos, function(i, val) {
                    salida += "<div class='box Ide_Cat box" + val.Id_Categoria + "' id=" + val
                        .Id_Categoria + ">";
                    salida += "<img src='" + val.Imagen + "' alt = '" + val.Id_Categoria +
                        "'>";
                    salida += "<h2 id='Nom'>" + val.Nombre + "</h2>";
                    salida += "<input type='hidden' Id ='Id_cat'value='" + val
                        .Id_Categoria + "'>";
                    salida += "</div>";
                });
                $("#Class2").append(salida);
            },
            error: function(jqXHR, status, error) {
                console.log("La solicitud a fallado: " + error);
                console.log("La solicitud a fallado: " + jqXHR);
                console.log("La solicitud a fallado: " + status);
            },
            complete: function(jqXHR, status, error) {
                //alert("Transaccion completa");
            }
        });
    });

and they're getting in here:

<div class="container-box " id="Class2">
  <div id="box" class="box">
    <input type="hidden" value="12">
  </div>
</div>
<div class=" row justify-content-center">
  <a href="#" id="a-submit">Enviar selecciones</a>
</div> 

To get multiple selections of categories (because that's what I think would work) displayed I have found several solutions but they don't work as I think I require, because the following: on a click event it does not retrieve the Id of the category the user is selecting but retrieves the Id_ of the first category only, regardless of whether the last one was selected:

var imagenes = document.querySelectorAll('#Class2');
    var titular = document.querySelector('#Id_cat');
    var Id_cts = new Array();
    $("#Abrir").ready(function() {
        for (var i = 0; i < imagenes.length; i++) {
            imagenes[i].addEventListener('click', function(){
                var ide = ('#Id_cat').val();
                var nombre = $('#Nom').val();
                console.log("El id de la categoria seleccionada es: "+ ide + " y el nombre es: " + nombre)
                var texto = "nombre";
            });       
        }
    });

And the following code only works by pressing the CTRL button although it still only retrieves the id_category of the first category regardless if you select the last one:

var selected_rows = []
    $("#Class2").click(function() {
        let clicked_row = $(this)
        if (clicked_row.hasClass('selected')) {
            clicked_row.removeClass('selected')
        } else {
            clicked_row.addClass('selected')
        }
    });

    $('#a-submit').click(function() {
        data = []
        selections = $('.selected')
        selections.each((index, element) => {
            let row_content = {
                Id_cat: $(element).find('#Id_cat').val(),
                lastname: $(element).find('#Nom').text(),
            }
            data.push(row_content)
        })
        console.log("Your selections:", data)
    })

In a nutshell:

Based on the JSON categories.

1-. I want to get the user's preferences

2.- There must be at least 5 or more categories selected.



source https://stackoverflow.com/questions/69365938/how-can-i-select-multiple-items-that-are-generated-in-real-time-with-js

Comments

Popular posts from this blog

Prop `className` did not match in next js app

I have written a sample code ( Github Link here ). this is a simple next js app, but giving me error when I refresh the page. This seems to be the common problem and I tried the fix provided in the internet but does not seem to fix my issue. The error is Warning: Prop className did not match. Server: "MuiBox-root MuiBox-root-1" Client: "MuiBox-root MuiBox-root-2". Did changes for _document.js, modified _app.js as mentioned in official website and solutions in stackoverflow. but nothing seems to work. Could someone take a look and help me whats wrong with the code? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console