I have 3 divs that have an onClick event. Then I want that when that div is pressed it will take the contents of the div that was pressed and then store it in a variable. how to make? I’ve tried it several times, but all the contents of the existing div are all called.
this my code. please help me
function uid(){
return Date.now().toString(12) + Math.random().toString(12).substr(2);
}
function loadContent() {
let $ = jQuery;
let api = "b97618b9d94f7f1090189b207f83ce52";
let title = $('#titless').val();
var url = "https://api.themoviedb.org/3/search/movie?api_key=" + api + "&language=en-US&query=" + title + "&page=1&include_adult=false";
fetch(url)
.then(res => res.json())
.then(data => {
$('#atas').empty();
$.each(data.results, function(i, item) {
$('#atas').append(
$('<div />', {
'class': 'col-md-2 my-2 mx-2 align-center',
'id': uid(),
'style': 'border: solid;',
'onclick' : 'loadGrab()',
'html': [
`<img class="card-img-top" src="https://image.tmdb.org/t/p/w600_and_h900_bestv2/${data.results[i].poster_path}">
<h3 class="title">${data.results[i].title}</h3>
<h1 class="ida">${data.results[i].id}</h1>
`
]
})
);
});
});
}
function loadGrab() {
let $ = jQuery;
let api = "b97618b9d94f7f1090189b207f83ce52";
let id = $('.ida').text();
let url = "https://api.themoviedb.org/3/movie/" + id + "?api_key="+ api +"&language=en-US";
fetch(url)
.then(res => res.json())
.then(res => {
$("#titleasd").text(res.title);
})
}
2
Answers
You can update your method call to include id that way you will always have a right id of clicked div.
First of all you should never share the api key.
The problem here is you are taking id using
$('.ida)
which takes all the textThe output for
$('.ida').text()
is "123"Alternative is to use a unique id for each element
or
write it like this
by giving the name to your
<div>
class. Using$(this)
, whichever<div>
is clicked will give you respective<div>'s
dataHere’s the fiddle for it https://jsfiddle.net/krb6u02y/