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

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...