Get data-id of HTML elements in Jquery

2

the code is perfect, the only problem is that when I want to pass the ids parameters to another function (show a modal), I throw them undefined.

$(document).ready(() => {
    const key = '98430029';
    
    $('#form').on('submit', (e) => {
        e.preventDefault();
        
        const input = $('#search').val();

        if(input === ''){
            $('#error').html('No se encontraron resultados'); 
        } else {
            $('#error').html(''); 

            getMovies(input)
        }
    })

    function getMovies(movie){

        axios.get('http://www.omdbapi.com/?apikey=${key}&s=${movie}')
            .then(response => {
                const movies = response.data.Search;
                let template = '';

                $.each(movies, (i, info) => {
                    
                    template += '
                        <div class="card col-12 col-md-4">
                            <img data-id="${info.imdbID}" 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="btn btn-success w-100" data-toggle="modal" data-target="#modal-details">
                                    Ver más
                                </a>
                            </div>
                        </div>                              
                    ';
                    
                })
               
                $('#content').html(template);
                
                  const listaId = $("img").map(function(){
                    return $(this).attr("data-id");
                  }).get();

                $('#detail').on('click', showDetails(listaId))
               
            })
            .catch(err => console.log(err))
    }
    function showDetails(id) {
        
        axios.get('http://www.omdbapi.com/?apikey=${key}&i=${id}')
        .then(response => {
            const info = response.data;
            console.log(info)
            let template = '
                <div class="modal fade" id="modal-details" tabindex="-1" role="dialog" aria-labelledby="modal-details" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="modal-details">${info.Title}</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <p>Description: ${info.Plot}</p>
                                <p><strong>Actors: ${info.Actors}</strong></p>
                                <p><i>Genre: ${info.Genre}</i></p>
                                <p><small>Year: ${info.Year}</small></p>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
             ';
            $("body").append(template);
        })
    }
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Buscador de Peliculas</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
    
    <div class="container">
        <h1 class="display-4 text-center py-4">Encuentra tu película</h1>
        <form class="text-center" id="form">
            <div class="form-group">
                <input type="text" 
                       class="form-control " 
                       id="search" aria-describedby="textSearch" 
                       placeholder="Nombre de tu película"
                >
            </div>
            <button type="submit" 
                    class="btn btn-success w-100" 
                    id="btn-search">
                    Buscar
            </button>
        </form>
        <div class="text-danger text-left py-2" id="error"></div>  
    </div>
    
    <div class="container">
        <div id="content" class="row"></div>   
    </div>
    


    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="js/app.js"></script>

</body>
</html>

This is the app ui

    
asked by Juan Morales 30.09.2018 в 20:43
source

1 answer

1

Effectively, as you are doing, it will always show you the first, you must go through each element and obtain its attribution data-id and store it in a variable:

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

console.log(lista);
.item{
  border:1px solid red;
  display:inline-block;
  height:60px;
  width:60px;
}

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

UPDATE

For your code I suggest you place a class and do not invoke it by id since many buttons will have the same id and will give you problems, according to my suggestion would look like this:

$.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>                              
                    ';

                })

As I added the class detail , the idea of all this is to make a click event where you can get said id and the attribute data-id moved it to the said button, now let's make the event click:

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

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

});

If you look at the click, I get the id of one of its attributes called data-id and then I pass it to the function showDetails()

I hope it serves you.

    
answered by 30.09.2018 / 20:54
source