Commit 0a9b0608 by Juan Montilla Committed by Manuel Ruiz Toribio

ajax

parent 83dd03bb
...@@ -38,6 +38,8 @@ $routes->match(['get', 'post'], '/registerAjax', [User::class, 'registerAjax']); ...@@ -38,6 +38,8 @@ $routes->match(['get', 'post'], '/registerAjax', [User::class, 'registerAjax']);
$routes->match(['get'], '/home', [User::class, 'user_ok']); $routes->match(['get'], '/home', [User::class, 'user_ok']);
$routes->get('/recipe/(:num)', 'RecipesController::view_recipe/$1');
// Ruta para obtener una imagen de una receta dado un id // Ruta para obtener una imagen de una receta dado un id
$routes->get('recipe/image/(:num)', 'RecipesController::show_image/$1'); $routes->get('recipe/image/(:num)', 'RecipesController::show_image/$1');
...@@ -46,15 +48,19 @@ $routes->get('/insert_recipe', 'InsertRecipeController::index'); ...@@ -46,15 +48,19 @@ $routes->get('/insert_recipe', 'InsertRecipeController::index');
$routes->match(['get', 'post'], '/search_ingredient', 'InsertRecipeController::search_ingredient'); $routes->match(['get', 'post'], '/search_ingredient', 'InsertRecipeController::search_ingredient');
$routes->post('/insert_recipe', 'InsertRecipeController::insert_recipe'); $routes->post('/insert_recipe', 'InsertRecipeController::insert_recipe');
// Ruta para la búsqueda de recetas
$routes->match(['get', 'post'], '/search_recipe', 'RecipesController::search_recipe'); $routes->match(['get', 'post'], '/search_recipe', 'RecipesController::search_recipe');
$routes->post('filter_recipes', 'RecipesController::get_filtered_recipes');
$routes->get('login','Pages::viewLogin'); $routes->get('login','Pages::viewLogin');
$routes->get('users','User::list'); $routes->get('users','User::list');
$routes->get('home','Pages::prueba'); $routes->get('home','Pages::prueba');
$routes->get('(:segment)', 'Home::index'); $routes->get('(:segment)', 'Home::index');
$routes->get('/recipe/(:num)', 'RecipesController::view_recipe/$1');
......
...@@ -25,7 +25,7 @@ class RecipesController extends Controller ...@@ -25,7 +25,7 @@ class RecipesController extends Controller
]; ];
return view('templates/header', $data) return view('templates/header', $data)
. view('pages/recipe_view', $data) . view('pages/recipe_view')
. view('templates/footer'); . view('templates/footer');
} }
...@@ -45,25 +45,26 @@ class RecipesController extends Controller ...@@ -45,25 +45,26 @@ class RecipesController extends Controller
} }
} }
//public function search_recipe() {
// Obtener la consulta de búsqueda desde el formulario
// $query = $this->request->getVar('query');
// Cargar el modelo de ingredientes (si no lo has hecho)
//$recipesModel = new \App\Models\RecipesModel();
// Buscar ingredientes en la base de datos que coincidan con la consulta
// $recipes = $recipesModel->search_recipe($query);
// Devolver los ingredientes coincidentes en formato JSON
// return $this->response->setJSON($recipes);
// }
public function search_recipe() public function search_recipe()
{ {
$query = $this->request->getVar('query'); $query = $this->request->getVar('query');
$recipesModel = new \App\Models\RecipesModel(); $recipesModel = new \App\Models\RecipesModel();
$recipes = $recipesModel->search_recipe($query); $recipes = $recipesModel->searchRecipe($query);
return $this->response->setJSON($recipes); return $this->response->setJSON($recipes);
} }
// En tu controlador de recetas
public function get_filtered_recipes() {
$recipesModel = new \App\Models\RecipesModel();
$vegan = $this->request->getPost('is_vegan') == "true" ? true : false;
$country = $this->request->getPost('origin');
$season = $this->request->getPost('season');
$filtered_recipes = $recipesModel->get_filtered_recipes($vegan, $country, $season);
return $this->response->setJSON($filtered_recipes);
}
} }
\ No newline at end of file
...@@ -3,7 +3,7 @@ namespace App\Models; ...@@ -3,7 +3,7 @@ namespace App\Models;
use CodeIgniter\Model; use CodeIgniter\Model;
class recipesModel extends Model class RecipesModel extends Model
{ {
protected $table = 'recipes'; protected $table = 'recipes';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
...@@ -11,7 +11,7 @@ class recipesModel extends Model ...@@ -11,7 +11,7 @@ class recipesModel extends Model
protected $returnType = 'object'; # 'object' or 'array' protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods # Fields that can be set during save, insert, or update methods
protected $allowedFields = ['id', 'name', 'season','origin','photo','is_vegan','description','instructions','link']; protected $allowedFields = ['id', 'name', 'season', 'origin', 'photo', 'is_vegan', 'description', 'instructions', 'link'];
protected $useTimestamps = false; # no timestamps on inserts and updates protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...) # Do not use validations rules (for the time being...)
protected $validationRules = []; protected $validationRules = [];
...@@ -35,7 +35,8 @@ class recipesModel extends Model ...@@ -35,7 +35,8 @@ class recipesModel extends Model
return $this->insert($data); return $this->insert($data);
} }
public function get_recipe_ingredients($recipe_id) { public function get_recipe_ingredients($recipe_id)
{
$builder = $this->db->table('recipes_ingredient'); $builder = $this->db->table('recipes_ingredient');
$builder->select('ingredient.name, ingredient.icon, recipes_ingredient.amount'); $builder->select('ingredient.name, ingredient.icon, recipes_ingredient.amount');
$builder->join('ingredient', 'recipes_ingredient.id_ingredient = ingredient.id'); $builder->join('ingredient', 'recipes_ingredient.id_ingredient = ingredient.id');
...@@ -43,21 +44,40 @@ class recipesModel extends Model ...@@ -43,21 +44,40 @@ class recipesModel extends Model
$query = $builder->get(); $query = $builder->get();
return $query->getResult(); return $query->getResult();
} }
/* public function search_recipe($query)
public function searchRecipe($query)
{ {
if ($query) { if ($query) {
// Seleccionar todas las columnas excepto 'photo'
$this->select('id, name, season, origin, is_vegan, description, instructions, link');
return $this->like('name', $query)->findAll(); return $this->like('name', $query)->findAll();
} }
return []; return [];
} */ }
public function search_recipe($query) public function get_filtered_recipes($vegan, $country, $season) {
{ $builder = $this->db->table('recipes');
if ($query) {
return $this->like('name', $query)->findAll(); if ($vegan) {
$builder->where('is_vegan', true);
} }
return [];
if (!empty($country)) {
$builder->where('origin', $country);
}
if (!empty($season)) {
$builder->where('season', $season);
}
$query = $builder->get();
return $query->getResult();
} }
} }
\ No newline at end of file
...@@ -42,9 +42,8 @@ ...@@ -42,9 +42,8 @@
<select id="origin" name="origin" class="form-control"> <select id="origin" name="origin" class="form-control">
<option value="Española">Española</option> <option value="Española">Española</option>
<option value="Francesa">Francesa</option> <option value="Francesa">Francesa</option>
<option value="Italiana">Italiana</option> <option value="Italiana">Japonesa</option>
<option value="Mexiana">Mexicana</option> <option value="Mexiana">Mexicana</option>
<option value="Americana">Americana</option>
<option value="China">China</option> <option value="China">China</option>
<option value="India">India</option> <option value="India">India</option>
</select> </select>
......
<?php <?php
function getYoutubeVideoId($url) { function getYoutubeVideoId($url)
{
$pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i'; $pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i';
preg_match($pattern, $url, $matches); preg_match($pattern, $url, $matches);
return isset($matches[1]) ? $matches[1] : null; return isset($matches[1]) ? $matches[1] : null;
...@@ -7,112 +8,124 @@ function getYoutubeVideoId($url) { ...@@ -7,112 +8,124 @@ function getYoutubeVideoId($url) {
?> ?>
<style> <style>
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
.container { .container {
max-width: 960px; max-width: 960px;
margin: 0 auto; margin: 0 auto;
padding: 20px; padding: 20px;
} }
.recipe-header { .recipe-header {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
margin-bottom: 30px; margin-bottom: 30px;
} }
.recipe-header img { .recipe-header img {
width: 100%; width: 100%;
max-width: 600px; max-width: 600px;
height: auto; height: auto;
object-fit: cover; object-fit: cover;
border-radius: 8px; border-radius: 8px;
} }
.ingredient-list { .ingredient-list {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
list-style-type: none; list-style-type: none;
padding: 0; padding: 0;
margin: 0; margin: 0;
margin-bottom: 30px; margin-bottom: 30px;
} }
.ingredient-item { .ingredient-item {
display: flex; display: flex;
align-items: center; align-items: center;
width: 50%; width: 50%;
padding: 5px 0; padding: 5px 0;
} }
.ingredient-item img { .ingredient-item img {
width: 30px; width: 30px;
height: 30px; height: 30px;
margin-right: 10px; margin-right: 10px;
} }
.instructions { .instructions {
white-space: pre-line; white-space: pre-line;
} }
.video-container { .video-container {
position: relative; position: relative;
padding-bottom: 56.25%; /* Relación de aspecto 16:9 */ padding-bottom: 56.25%;
height: 0; /* Relación de aspecto 16:9 */
overflow: hidden; height: 0;
} overflow: hidden;
}
.video-container iframe {
position: absolute; .video-container iframe {
top: 0; position: absolute;
left: 0; top: 0;
width: 100%; left: 0;
height: 100%; width: 100%;
} height: 100%;
</style> }
</style>
<main id="mainview" class="mainview">
<main id="main" class="main">
<section class="section dashboard"> <section class="section dashboard">
<div class="container"> <div class="container">
<div class="recipe-header"> <div class="recipe-header">
<h1>Receta:</h1> <h1>
<h1><?php echo $recipe->name; ?></h1> <?php echo $recipe->name; ?>
<img src="<?php echo base_url('recipe/image/' . $recipe->id); ?>" alt="<?php echo $recipe->name; ?>" /> </h1>
</div> <img src="<?php echo base_url('recipe/image/' . $recipe->id); ?>" alt="<?php echo $recipe->name; ?>" />
</div>
<p><?php echo $recipe->description; ?></p>
<p>
<h2>Ingredientes</h2> <?php echo $recipe->description; ?>
<ul class="ingredient-list"> </p>
<?php foreach ($ingredients as $ingredient) { ?>
<li class="ingredient-item"> <h2>Ingredientes</h2>
<img src="../imagenes/ingredientes/<?php echo $ingredient->icon; ?>" alt="<?php echo $ingredient->name; ?>" /> <ul class="ingredient-list">
<span><?php echo $ingredient->name; ?>: <?php echo $ingredient->amount; ?></span> <?php foreach ($ingredients as $ingredient) { ?>
</li> <li class="ingredient-item">
<?php } ?> <img src="../imagenes/ingredientes/<?php echo $ingredient->icon; ?>"
</ul> alt="<?php echo $ingredient->name; ?>" />
<span>
<h2>Instrucciones</h2> <?php echo $ingredient->name; ?>:
<p class="instructions"><?php echo $recipe->instructions; ?></p> <?php echo $ingredient->amount; ?>
</span>
<?php if (!empty($recipe->link)): ?> </li>
<?php $videoId = getYoutubeVideoId($recipe->link); ?> <?php } ?>
<?php if ($videoId): ?> </ul>
<h2>Video de la receta</h2>
<div class="video-container"> <h2>Instrucciones</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $videoId; ?>" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <p class="instructions">
</div> <?php echo $recipe->instructions; ?>
</p>
<?php if (!empty($recipe->link)): ?>
<?php $videoId = getYoutubeVideoId($recipe->link); ?>
<?php if ($videoId): ?>
<h2>Video de la receta</h2>
<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $videoId; ?>"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
<?php endif; ?>
<?php endif; ?> <?php endif; ?>
<?php endif; ?> </div>
</div>
</section> </section>
</main><!-- End #main --> </main><!-- End #main -->
\ No newline at end of file
...@@ -32,8 +32,8 @@ ...@@ -32,8 +32,8 @@
<link href="<?= base_url("css/style.css") ?>" rel="stylesheet"> <link href="<?= base_url("css/style.css") ?>" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.4.min.js" <script src="https://code.jquery.com/jquery-3.6.4.min.js"
integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script> integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</head> </head>
...@@ -55,15 +55,15 @@ ...@@ -55,15 +55,15 @@
<i class="bi bi-list toggle-sidebar-btn"></i> <i class="bi bi-list toggle-sidebar-btn"></i>
</div><!-- End Logo --> </div><!-- End Logo -->
<!-- Barra de búsqueda -->
<div class="search-bar"> <div class="search-bar">
<form class="search-form d-flex align-items-center" method="POST" action="#"> <form class="search-form d-flex align-items-center" method="POST" action="#">
<input type="text" id="search-query" name="query" placeholder="Buscar por receta..." <input type="text" id="search-query" name="query" placeholder="Buscar por receta..."
title="Enter search keyword"> title="Enter search keyword" >
</form> </form>
<div id="recipe_dropdown" class="recipe-dropdown"> <ul id="recipe_list" class="ingredients-list list-unstyled"></ul>
<ul id="recipe_list" class="recipe-list list-unstyled"></ul> </div>
</div> <!-- Fin barra de búsqueda -->
</div>
...@@ -154,4 +154,165 @@ ...@@ -154,4 +154,165 @@
</ul> </ul>
</nav><!-- End Icons Navigation --> </nav><!-- End Icons Navigation -->
</header><!-- End Header --> </header><!-- End Header -->
\ No newline at end of file
<!-- ======= Sidebar ======= -->
<aside id="sidebar" class="sidebar">
<ul class="sidebar-nav" id="sidebar-nav">
<li class="nav-item">
<a class="nav-link " href="index.html">
<i class="bi bi-grid"></i>
<span>Recetas</span>
</a>
</li><!-- End Dashboard Nav -->
<!-- Filtro 1-->
<li class="nav-item">
<a class="nav-link collapsed" data-bs-target="#tables-nav" data-bs-toggle="collapse" href="#">
<i class="bi bi-layout-text-window-reverse"></i><span>Filtro Vegano</span><i
class="bi bi-chevron-down ms-auto"></i>
</a>
<ul id="tables-nav" class="nav-content collapse " data-bs-parent="#sidebar-nav">
<!--Contenido del dropdown-->
<ul class="vegan-cboxtags">
<li>
<input type="checkbox" id="checkboxOne" value="Order one" onchange="updateRecipeList()">
<label for="checkboxOne">Recetas Veganas </label>
</li>
</ul>
</ul>
</li><!-- Fin Filtro 1 -->
<!-- Filtro 1-->
<li class="nav-item">
<a class="nav-link collapsed" data-bs-target="#tables-nav2" data-bs-toggle="collapse" href="#">
<i class="bi bi-layout-text-window-reverse"></i><span>Filtro 2</span><i
class="bi bi-chevron-down ms-auto"></i>
</a>
<ul id="tables-nav2" class="nav-content collapse " data-bs-parent="#sidebar-nav">
<!--Contenido del dropdown-->
<ul class="indian-cboxtags">
<li>
<input type="checkbox" id="checkboxFour" value="Order four" onchange="updateRecipeList()">
<label for="checkboxFour">India </label>
</li>
</ul>
<ul class="french-cboxtags">
<li>
<input type="checkbox" id="checkboxFive" value="Order five" onchange="updateRecipeList()">
<label for="checkboxFive">Francia </label>
</li>
</ul>
<ul class="chinese-cboxtags">
<li>
<input type="checkbox" id="checkboxSix" value="Order six" onchange="updateRecipeList()">
<label for="checkboxSix">China </label>
</li>
</ul>
<ul class="mexican-cboxtags">
<li>
<input type="checkbox" id="checkboxSeven" value="Order seven" onchange="updateRecipeList()">
<label for="checkboxSeven">México </label>
</li>
</ul>
<ul class="spanish-cboxtags">
<li>
<input type="checkbox" id="checkboxEight" value="Order eigth" onchange="updateRecipeList()">
<label for="checkboxEight">España </label>
</li>
</ul>
<ul class="japanese-cboxtags">
<li>
<input type="checkbox" id="checkboxNine" value="Order nine" onchange="updateRecipeList()">
<label for="checkboxNine">Japón </label>
</li>
</ul>
</ul>
</li><!-- Fin Filtro 1 -->
<li class="nav-item">
<a class="nav-link collapsed" data-bs-target="#tables-nav3" data-bs-toggle="collapse" href="#">
<i class="bi bi-layout-text-window-reverse"></i><span>Estaciones</span><i
class="bi bi-chevron-down ms-auto"></i>
</a>
<ul id="tables-nav3" class="nav-content collapse " data-bs-parent="#sidebar-nav">
<!--Contenido del dropdown-->
<ul class="winter-cboxtags">
<li>
<input type="checkbox" id="checkboxTen" value="Order ten" onchange="updateRecipeList()">
<label for="checkboxTen">Invierno </label>
</li>
</ul>
<ul class="spring-cboxtags">
<li>
<input type="checkbox" id="checkboxEleven" value="Order eleven" onchange="updateRecipeList()">
<label for="checkboxEleven">Primavera </label>
</li>
</ul>
<ul class="summer-cboxtags">
<li>
<input type="checkbox" id="checkboxTwelve" value="Order twelve" onchange="updateRecipeList()">
<label for="checkboxTwelve">Verano </label>
</li>
</ul>
<ul class="autumn-cboxtags">
<li>
<input type="checkbox" id="checkbox13" value="Order 13" onchange="updateRecipeList()">
<label for="checkbox13">Otoño </label>
</li>
</ul>
</ul>
</li><!-- Fin Filtro 1 -->
<li class="nav-item">
<a class="nav-link collapsed" href="/insert_recipe">
<i class="bi bi-file-earmark"></i>
<span>Subir receta</span>
</a>
</li><!-- End Profile Page Nav -->
<li class="nav-item">
<a class="nav-link collapsed" href="https://www.instagram.com/salvaperfectti/">
<i class="bi bi-envelope"></i>
<span>Contacto</span>
</a>
</li><!-- End Contact Page Nav -->
<li class="nav-item">
<a class="nav-link collapsed" href="/login">
<i class="bi bi-box-arrow-in-right"></i>
<span>Registro/Login</span>
</a>
</li><!-- End Login Page Nav -->
<li class="nav-item">
<a class="nav-link collapsed" href="http://www.homerswebpage.com/">
<i class="bi bi-dash-circle"></i>
<span>Error 404</span>
</a>
</li><!-- End Error 404 Page Nav -->
</ul>
</aside><!-- End Sidebar-->
\ No newline at end of file
...@@ -360,6 +360,26 @@ h6 { ...@@ -360,6 +360,26 @@ h6 {
.header .search-bar { .header .search-bar {
min-width: 360px; min-width: 360px;
padding: 0 20px; padding: 0 20px;
position: relative;
}
#recipe_list {
position: absolute;
top: 100%;
left: 0;
z-index: 1;
width: 100%;
max-height: 200px;
overflow-y: auto;
background-color: #fff;
border-top: none;
border-radius: 0 0 .25rem .25rem;
padding: 0;
margin: 0;
}
.recipe-item {
cursor: pointer;
} }
@media (max-width: 1199px) { @media (max-width: 1199px) {
...@@ -789,10 +809,7 @@ h6 { ...@@ -789,10 +809,7 @@ h6 {
} }
/* Info Cards */ /* Info Cards */
.dashboard .info-card { s
padding-bottom: 10px;
}
.dashboard .info-card h6 { .dashboard .info-card h6 {
font-size: 28px; font-size: 28px;
color: #012970; color: #012970;
...@@ -904,12 +921,6 @@ h6 { ...@@ -904,12 +921,6 @@ h6 {
padding-left: 0; padding-left: 0;
} }
.recipe-card-link {
display: block;
text-decoration: none;
color: inherit;
}
.dashboard .news p { .dashboard .news p {
font-size: 14px; font-size: 14px;
color: #777777; color: #777777;
......
...@@ -11,21 +11,21 @@ const recipeForm = document.querySelector("form.my-form"); ...@@ -11,21 +11,21 @@ const recipeForm = document.querySelector("form.my-form");
recipeForm.addEventListener("submit", function (event) { recipeForm.addEventListener("submit", function (event) {
const selectedIngredients = Array.from(document.querySelectorAll(".selected-ingredient")); const selectedIngredients = Array.from(document.querySelectorAll(".selected-ingredient"));
const ingredientsData = selectedIngredients.map((ingredientElem) => { const ingredientsData = selectedIngredients.map((ingredientElem) => {
return { return {
id: ingredientElem.dataset.ingredientId, id: ingredientElem.dataset.ingredientId,
amount: ingredientElem.querySelector(".ingredient-amount").textContent, amount: ingredientElem.querySelector(".ingredient-amount").textContent,
}; };
}); });
const hiddenInput = document.createElement("input"); const hiddenInput = document.createElement("input");
hiddenInput.type = "hidden"; hiddenInput.type = "hidden";
hiddenInput.name = "selected_ingredients"; hiddenInput.name = "selected_ingredients";
hiddenInput.value = JSON.stringify(ingredientsData); hiddenInput.value = JSON.stringify(ingredientsData);
recipeForm.appendChild(hiddenInput); recipeForm.appendChild(hiddenInput);
}); });
// Array para almacenar palabras clave seleccionadas // Array para almacenar palabras clave seleccionadas
let ingredients = []; let ingredients = [];
...@@ -35,7 +35,7 @@ function searchIngredients(query) { ...@@ -35,7 +35,7 @@ function searchIngredients(query) {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest' // Añadir esta línea 'X-Requested-With': 'XMLHttpRequest'
}, },
body: 'query=' + encodeURIComponent(query) body: 'query=' + encodeURIComponent(query)
}) })
...@@ -109,38 +109,38 @@ function removeIngredient(ingredient) { ...@@ -109,38 +109,38 @@ function removeIngredient(ingredient) {
function updateSelectedIngredients() { function updateSelectedIngredients() {
// Limpiar el campo de selección // Limpiar el campo de selección
selectedIngredients.innerHTML = ''; selectedIngredients.innerHTML = '';
// Agregar cada ingrediente seleccionado al campo de selección // Agregar cada ingrediente seleccionado al campo de selección
ingredients.forEach(function (ingredient) { ingredients.forEach(function (ingredient) {
const ingredientElement = document.createElement('div'); const ingredientElement = document.createElement('div');
ingredientElement.classList.add('selected-ingredient'); ingredientElement.classList.add('selected-ingredient');
ingredientElement.setAttribute('data-ingredient-id', ingredient.id); ingredientElement.setAttribute('data-ingredient-id', ingredient.id);
// Crear el elemento de imagen para el icono del ingrediente // Crear el elemento de imagen para el icono del ingrediente
const iconElement = document.createElement('img'); const iconElement = document.createElement('img');
iconElement.classList.add('ingredient-icon'); iconElement.classList.add('ingredient-icon');
iconElement.src = '../imagenes/ingredientes/' + ingredient.icon; iconElement.src = '../imagenes/ingredientes/' + ingredient.icon;
ingredientElement.appendChild(iconElement); ingredientElement.appendChild(iconElement);
// Agregar el nombre del ingrediente y la cantidad // Agregar el nombre del ingrediente y la cantidad
const ingredientNameAndQuantity = document.createElement('span'); const ingredientNameAndQuantity = document.createElement('span');
ingredientNameAndQuantity.textContent = `${ingredient.name} (${ingredient.quantity})`; ingredientNameAndQuantity.textContent = `${ingredient.name} (${ingredient.quantity})`;
ingredientNameAndQuantity.classList.add('ingredient-amount'); ingredientNameAndQuantity.classList.add('ingredient-amount');
ingredientElement.appendChild(ingredientNameAndQuantity); ingredientElement.appendChild(ingredientNameAndQuantity);
// Agregar el botón para eliminar el ingrediente // Agregar el botón para eliminar el ingrediente
const removeBtn = document.createElement('button'); const removeBtn = document.createElement('button');
removeBtn.classList.add('btn', 'btn-danger', 'btn-sm'); removeBtn.classList.add('btn', 'btn-danger', 'btn-sm');
removeBtn.textContent = 'x'; removeBtn.textContent = 'x';
removeBtn.addEventListener('click', function () { removeBtn.addEventListener('click', function () {
removeIngredient(ingredient); removeIngredient(ingredient);
}); });
ingredientElement.appendChild(removeBtn); ingredientElement.appendChild(removeBtn);
selectedIngredients.appendChild(ingredientElement); selectedIngredients.appendChild(ingredientElement);
}); });
} }
...@@ -154,43 +154,43 @@ ingredientSearch.addEventListener('input', function (event) { ...@@ -154,43 +154,43 @@ ingredientSearch.addEventListener('input', function (event) {
var inputPhoto = document.getElementById('photo'); var inputPhoto = document.getElementById('photo');
var imageUploadContainer = document.querySelector('.image-upload-container'); var imageUploadContainer = document.querySelector('.image-upload-container');
inputPhoto.addEventListener('change', function(event) { inputPhoto.addEventListener('change', function (event) {
displayImagePreview(event.target.files[0]); displayImagePreview(event.target.files[0]);
}); });
imageUploadContainer.addEventListener('dragover', function(event) { imageUploadContainer.addEventListener('dragover', function (event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
event.dataTransfer.dropEffect = 'copy'; event.dataTransfer.dropEffect = 'copy';
}); });
imageUploadContainer.addEventListener('drop', function(event) { imageUploadContainer.addEventListener('drop', function (event) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (event.dataTransfer.files.length > 0) { if (event.dataTransfer.files.length > 0) {
displayImagePreview(event.dataTransfer.files[0]); displayImagePreview(event.dataTransfer.files[0]);
inputPhoto.files = event.dataTransfer.files; inputPhoto.files = event.dataTransfer.files;
} }
}); });
function displayImagePreview(file) { function displayImagePreview(file) {
var reader = new FileReader(); var reader = new FileReader();
reader.onload = function() { reader.onload = function () {
var output = document.getElementById('image-preview'); var output = document.getElementById('image-preview');
output.src = reader.result; output.src = reader.result;
output.style.display = 'block'; output.style.display = 'block';
} }
reader.readAsDataURL(file); reader.readAsDataURL(file);
} }
document.getElementById('photo').addEventListener('change', function(event) { document.getElementById('photo').addEventListener('change', function (event) {
var reader = new FileReader(); var reader = new FileReader();
reader.onload = function() { reader.onload = function () {
var output = document.getElementById('image-preview'); var output = document.getElementById('image-preview');
output.src = reader.result; output.src = reader.result;
output.style.display = 'block'; output.style.display = 'block';
} }
reader.readAsDataURL(event.target.files[0]); reader.readAsDataURL(event.target.files[0]);
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment