I have a javascript file that displays a variable number of videos embedded from youtube and displayed in a grid. I need the users to be able to select one video and click submit where I will will store the src link of that video in a variable.
Below is the related javascript portion:
playListItems.forEach(item => {
const videoId = item.snippet.resourceId.videoId;
output += `
<div class="col s3">
<iframe width="100%" id="videoFrame" height="auto"
src="https://www.youtube.com/embed/${videoId}?rel=0" frameborder="0" encrypted-media" >
</iframe></div>
`;
}
HTML:
<form id="form1">
<div class="input-field">
<input type="submit" id="but1" value="Save Selection">
</div>
</form>
How do I do that using an event handler or any other possible solution?
why not use const videoId
as the id
of each iframe? Because you can't use an id more then once. Then in an onclick
handler of each iframe element you can fire a function that sets the value of <input type="submit" id="but1" value="Save Selection">
to this.id
.
Like so:
playListItems.forEach(item => {
const videoId = item.snippet.resourceId.videoId;
output += '<div class="col s3">
<iframe width="100%" id="${videoId}" height="auto"
src="https://www.youtube.com/embed/${videoId}?rel=0" frameborder="0" encrypted-media" onclick='submitVid(this.id);'>
</iframe></div>';
}
Then the submitVid(video)
function will look something like this:
function submitVid(video) {
//the video variable will hold this.id or the videoId
//Here you can do whatever you want with video.
//Full video id:
var url = "https://www.youtube.com/embed/" + video + "?rel=0";
//pass value to a textfield to submit
document.getElementById("textfield").value = video;
}
A better is to just store the videoId
and not the full url. It saves space and it is faster.
Hope this helps! If not, please comment