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

Time:09-29

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.

CodePudding user response:

Consider the following example.

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

$(function() {
  function makeSalidas(data, target) {
    var cid = data.Id_Categoria;
    var salidas = $("<div>", {
      class: "box Ide_Cat box-"   cid,
      id: "box-"   cid,
    }).data("box", data);
    $("<img>", {
      src: data.Imagen,
      alt: "Box "   cid
    }).appendTo(salidas);
    $("<h2>", {
      id: "nom-"   cid
    }).html(data.Nombre).appendTo(salidas);
    $("<input>", {
      type: "hidden",
      id: "Id_cat-"   cid
    }).appendTo(salidas);
    if (target == undefined) {
      return salidas;
    } else {
      salidas.appendTo(target);
    }
  }

  $("#Class2").empty();
  $.each(myData, function(i, v) {
    makeSalidas(v, "#Class2");
  });

  $("#Class2").on("click", ".box", function(event) {
    $(this).toggleClass("selected");
  });

  $("#a-submit").click(function(event) {
    event.preventDefault();
    var selected = [];
    $(".box.selected").each(function(i, el) {
      selected.push($(el).data("box").Id_Categoria);
    });
    console.log(selected);
  });
});
.box {
  width: 270px;
  height: 280px;
  border: 2px solid transparent;
  border-radius: 10px;
  text-align: center;
  margin: 3px;
  padding: 3px;
}

.box.selected {
  border-color: red;
}

.box.selected h2:after {
  content: '';
  display: block;
  width: 7px;
  height: 15px;
  border: solid red;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  margin-left: 135px;
  margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container-box" id="Class2">
</div>

<div class="row justify-content-center">
  <a href="#" id="a-submit">Enviar selecciones</a>
</div>

With a simple function, we can use a single items Data and make all the HTML elements we want. Remember that IDs in HTML must be unique.

Using .data(), we can store the Data for each with the Box for easy reference later.

We can use .toggleClass() to add/remove a class when the user wants to select a specific item. We can then use that same Class name to help identify which items were selected when we submit the data.

When submitted, I setup an array and entered the Category IDs into the array so that it can more easily be posted to an API or worked with in a Database.

Your script will be more like the following.

$("#Abrir").click(function(event) {
  $.getJSON("prueba.php", function(datos){
    $("#Class2").empty();
    $.each(datos, function(i, v) {
      makeSalidas(v, "#Class2");
    });
  });
});
  • Related