Obtener data-id de elementos HTML en Jquery

publicado por: Anonymous

el código anda perfecto, el único problema es que cuando quiero pasar por parámetros los ids a otra función(mostrar un modal), me los tira undefined.

_x000D_

_x000D_

$(document).ready(() => {_x000D_
    const key = '98430029';_x000D_
    _x000D_
    $('#form').on('submit', (e) => {_x000D_
        e.preventDefault();_x000D_
        _x000D_
        const input = $('#search').val();_x000D_
_x000D_
        if(input === ''){_x000D_
            $('#error').html('No se encontraron resultados'); _x000D_
        } else {_x000D_
            $('#error').html(''); _x000D_
_x000D_
            getMovies(input)_x000D_
        }_x000D_
    })_x000D_
_x000D_
    function getMovies(movie){_x000D_
_x000D_
        axios.get(`http://www.omdbapi.com/?apikey=${key}&s=${movie}`)_x000D_
            .then(response => {_x000D_
                const movies = response.data.Search;_x000D_
                let template = '';_x000D_
_x000D_
                $.each(movies, (i, info) => {_x000D_
                    _x000D_
                    template += `_x000D_
                        <div class="card col-12 col-md-4">_x000D_
                            <img data-id="${info.imdbID}" class="card-img-top" src="${info.Poster === 'N/A' ? '': info.Poster}">_x000D_
                            <div class="card-body text-center">_x000D_
                                <h5 class="card-title">${info.Title}</h5>_x000D_
                                <a id="detail" class="btn btn-success w-100" data-toggle="modal" data-target="#modal-details">_x000D_
                                    Ver más_x000D_
                                </a>_x000D_
                            </div>_x000D_
                        </div>                              _x000D_
                    `;_x000D_
                    _x000D_
                })_x000D_
               _x000D_
                $('#content').html(template);_x000D_
                _x000D_
                  const listaId = $("img").map(function(){_x000D_
                    return $(this).attr("data-id");_x000D_
                  }).get();_x000D_
_x000D_
                $('#detail').on('click', showDetails(listaId))_x000D_
               _x000D_
            })_x000D_
            .catch(err => console.log(err))_x000D_
    }_x000D_
    function showDetails(id) {_x000D_
        _x000D_
        axios.get(`http://www.omdbapi.com/?apikey=${key}&i=${id}`)_x000D_
        .then(response => {_x000D_
            const info = response.data;_x000D_
            console.log(info)_x000D_
            let template = `_x000D_
                <div class="modal fade" id="modal-details" tabindex="-1" role="dialog" aria-labelledby="modal-details" aria-hidden="true">_x000D_
                    <div class="modal-dialog" role="document">_x000D_
                        <div class="modal-content">_x000D_
                            <div class="modal-header">_x000D_
                                <h5 class="modal-title" id="modal-details">${info.Title}</h5>_x000D_
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">_x000D_
                                  <span aria-hidden="true">&times;</span>_x000D_
                                </button>_x000D_
                            </div>_x000D_
                            <div class="modal-body">_x000D_
                                <p>Description: ${info.Plot}</p>_x000D_
                                <p><strong>Actors: ${info.Actors}</strong></p>_x000D_
                                <p><i>Genre: ${info.Genre}</i></p>_x000D_
                                <p><small>Year: ${info.Year}</small></p>_x000D_
                            </div>_x000D_
                            <div class="modal-footer">_x000D_
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>_x000D_
                            </div>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                </div>_x000D_
             `;_x000D_
            $("body").append(template);_x000D_
        })_x000D_
    }_x000D_
})

_x000D_

<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <title>Buscador de Peliculas</title>_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">_x000D_
</head>_x000D_
<body>_x000D_
    _x000D_
    <div class="container">_x000D_
        <h1 class="display-4 text-center py-4">Encuentra tu película</h1>_x000D_
        <form class="text-center" id="form">_x000D_
            <div class="form-group">_x000D_
                <input type="text" _x000D_
                       class="form-control " _x000D_
                       id="search" aria-describedby="textSearch" _x000D_
                       placeholder="Nombre de tu película"_x000D_
                >_x000D_
            </div>_x000D_
            <button type="submit" _x000D_
                    class="btn btn-success w-100" _x000D_
                    id="btn-search">_x000D_
                    Buscar_x000D_
            </button>_x000D_
        </form>_x000D_
        <div class="text-danger text-left py-2" id="error"></div>  _x000D_
    </div>_x000D_
    _x000D_
    <div class="container">_x000D_
        <div id="content" class="row"></div>   _x000D_
    </div>_x000D_
    _x000D_
_x000D_
_x000D_
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>_x000D_
    <script src="js/app.js"></script>_x000D_
_x000D_
</body>_x000D_
</html>

_x000D_

_x000D_

_x000D_

Este el ui de app
Este es el ui de la app

solución

Efectivamente como lo estas haciendo siempre te mostrará el primero, debes recorrer cada elemento y obtener su atribuo data-id y almacenarlo en una variable:

_x000D_

_x000D_

var lista = $("img").map(function(){_x000D_
              return $(this).attr("data-id");_x000D_
            }).get();_x000D_
_x000D_
console.log(lista);

_x000D_

.item{_x000D_
  border:1px solid red;_x000D_
  display:inline-block;_x000D_
  height:60px;_x000D_
  width:60px;_x000D_
}_x000D_
_x000D_
.item:hover{_x000D_
  cursor:pointer;_x000D_
}

_x000D_

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<img data-id="1" class="item" src="..." alt="imagen1">_x000D_
<img data-id="2" class="item" src="..." alt="imagen2">_x000D_
<img data-id="3" class="item" src="..." alt="imagen3">_x000D_
<img data-id="4" class="item" src="..." alt="imagen4">

_x000D_

_x000D_

_x000D_

UPDATE

Para tu código sugiero que le coloques una clase y no lo invoques por el id ya que muchos botones tendrán el mismo id y te va a dar problemas, según mi sugerencia quedaría así:

$.each(movies, (i, info) => {

                    template += `
                        <div class="card col-12 col-md-4">
                            <img class="card-img-top" src="${info.Poster === 'N/A' ? '': info.Poster}">
                            <div class="card-body text-center">
                                <h5 class="card-title">${info.Title}</h5>
                                <a id="detail" class="detail btn btn-success w-100" data-target="#modal-details" data-id="${info.imdbID}">
                                    Ver más
                                </a>
                            </div>
                        </div>                              
                    `;

                })

Como le agregué la clase detail, la idea de todo esto es hacer un evento click donde puedas obtener dicho id y el atributo data-id lo movi para el dicho botón, ahora hagamos el evento click:

$(".detail").click(function(){

  let id = $(this).attr("data-id");
  showDetails(id);

});

Si te fijas al darle click obtengo el id de uno de sus atributos llamado data-id y luego se lo paso a la función showDetails()

Espero te sirva.

Respondido por: Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *