JavaScript - BUCLE FOR DENTRO DE UN SELETC

 
Vista:
sin imagen de perfil

BUCLE FOR DENTRO DE UN SELETC

Publicado por Miriam (6 intervenciones) el 24/11/2022 14:22:29
Hola.

Necesito meter un for que tengo hecho dentro de un select:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Consulta a la API para obtener los tipos de recetas
//Forma de atacar al servicio REST
let xmlHttp = new XMLHttpRequest();
xmlHttp.open(
  "GET",
  "http://localhost/recetarioappweb/sistema/API/ingredientes.php",
  false
); // false for synchronous request
xmlHttp.send(null);
//console.log(xmlHttp.responseText);
 
//Convertimos en objeto
let resultadoIngredientes = JSON.parse(xmlHttp.responseText);
 
let html = "<label>Seleccione uno o varios ingredientes: </label> <br><br>";
 
for (let i = 0; i < resultadoIngredientes.length; i++) {
  html += `<div class='form-check form-check-inline'>
    <input class='form-check-input' type='checkbox' value='${resultadoIngredientes[i].id}' id='inlineCheckbox1' name='ingredientes[]'>
    <label class='form-check-label' for='inlineCheckbox1'>
      ${resultadoIngredientes[i].nombre}
    </label>
  </div>`;
}
 
document.getElementById("ingredientes").innerHTML += html;

Ahora los ingredientes me salen así:


Captura

Pero necesito mostrar los ingredientes en un select en lugar de que aparezcan checkbox y al lado un input de texto libre para la cantidad. Además también necesito poner un botón añadir para ir añadiendo más ingredientes.

Si le doy al botón me mostrará otro select con otro input al lado para la cantidad.

La idea es que salga algo así:

Posible-vista

He intentado mil formas pero me da error, ¿alguien me puede ayuda?

Había pensado algo así pero no consigo montarlo según mi código:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
!empty($_POST) && var_dump($_POST);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Crear/Editar receta</h1>
<form method="post">
    Nombre: <input name="nombre_receta"><br />
    (Otros campos de la receta)
    <h2>Añadir ingredientes:</h2>
    <button id="add_ingrediente">Añadir</button>
    <div id="form_ingredientes">
    </div>
    <div><input type="submit" value="Enviar"></div>
</form>
<script>
    let cont = 0;
    document.querySelector('#add_ingrediente').addEventListener('click', function (event) {
        event.preventDefault();
        text = '<div>\
                    <div style="display: inline">\
                    <select name="ingredientes['+cont+'][\'id_ingrediente\']" id="">\
                        <option value="">Selecciona ingrediente</option>\
                        <option value="1">Leche</option>\
                        <option value="2">Huevo</option>\
                        <option value="3">Arroz</option>\
                    </select>\
                    </div>\
                    <div style="display: inline">\
                        <input name="ingredientes['+cont+'][\'cantidad\']" type="text">\
                    </div>\
                </div>';
        document.querySelector('#form_ingredientes').insertAdjacentHTML("beforeend", text);
        cont++;
    });
</script>
</body>
</html>



Gracias, saludos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 40
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

BUCLE FOR DENTRO DE UN SELETC

Publicado por Marlon (90 intervenciones) el 25/11/2022 00:55:57
Porque usas PHP???

En ves de insertar html como texto podrías hacer uso de JavaScript.
lo que podrias hacer es que cada vez que pulsan el boton añadir se crea los elementos en el DOM de la siguiente forma.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const items = ["arroz", "huevos", "leche", "papa", "pez", "carne"]; // Listado de ingredientes como prueba
const divItems = document.getElementById("form_ingredientes"); // Seleccionamos el div para mas tarde agregarle los SELECT
const addItemsButton = document.getElementById("add_ingrediente"); //El button para agregarle la funcion de crear los elementos
let selectAttCounter = 0; // variable que nos sirve para dar nombres a los atributos en cada iteración
 
addItemsButton.addEventListener('click', addItem); // agregamos la funcion al boton cada que se haga "click"
 
 
//funcion para crear elemntos cada que se haga un click en el boton añadir
function addItem(){
    let divItem = document.createElement("div"); //Se crea el div que va a contener select y input
    let inputItem = document.createElement("input"); //Se crea el input que tendra la cantidad de cada ingrediente
    inputItem.setAttribute('type', "text"); // se le agrega el atributo texto
    inputItem.name = "input" + selectAttCounter // se le agrega el atributo name para que el form lo envie en los datos
    let listItems = document.createElement("select"); // se crea el select
    listItems.id = "select" + selectAttCounter; // se le agrega el atributo id para manejar en caso de ser necesario
    listItems.name = "select" + selectAttCounter; // se le agrega el atributo name para que el form lo envie en los datos
   //aqui se itera sobre cada elemento del array items
    items.forEach(element => {
        let option = document.createElement("option"); //se crea el la opcion para agregar al Select
        option.value = element; // se le agrega el valor
        option.text = element; // se agrega el texto de la opcion que ve el usuario.
        listItems.appendChild(option); // se añade al Select
    });
    divItem.appendChild(listItems) //Se añade el select al div contenedor
    divItem.appendChild(inputItem)// se añade el input al div contenedor
    divItems.appendChild(divItem); //se añade el div contenedor al div del form para que aparezca
    selectAttCounter++; //se incrementa la variable para cambiar los atributos del select y que no haya inconvenientes con el manejo de los datos que envia el form
}


Espero te funcione esta forma de hacerlo. cualquier cosa preugntas. Saludos!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar