Transform your HTML table into clickable links

https://i.sstatic.net/forOz.jpg

Just starting out in html.
Here's my html code that retrieves Json data from the server and displays it in an HTML table format.

Could someone modify my html code to include a button between Video Link and Video Image, so that when the button is clicked, it plays the corresponding YouTube video with the video ID from the same row.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('https://api.myjson.com/bins/hy7g0', function(data) {
       $.each(data.videoLectureListing, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.Id + "</td>" +
           "<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" + "<td>" + f.video + "</td>" + "<td>" + f.image + "</td>" +
           "<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td>"+ "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="25">
  <thead>
            <th>ID</th> 
            <th>VIDEO NAME</th>
            <th>DATE</th>
            <th>TIME</th>
<th>VIDEO LINK</th>
<th>VIDEO IMAGE</th>
            <th>DURATION</th>
            <th>LIVE STATUS</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

I've searched a lot on the internet but couldn't find any solutions, please help me solve this issue. Thank you.

Answer №1

I found a little spare time, so I came up with this solution to address your issue:

        const fields = ['Id', 'videoName', 'date', 'time', 'videoLink', 'image', 'videoDuration', 'liveStatus'];
    var tableBody = document.getElementById('myTableBody');

    fetch('https://api.myjson.com/bins/hy7g0').then(response => {
        return response.json().then(data => {
            createTable(data.videoLectureListing);
        })
    });

    function createTable(fullData) {
        if (fullData) {
            return fullData.forEach(videoData => {
                let newRow = constructRow(videoData);
                tableBody.appendChild(newRow)
            })
        }
    }

    function constructRow(videoData) {
        let newRow = document.createElement('tr');
        fields.forEach(field => {
            let elem = undefined;
            if (field === 'videoLink') {
                elem = generateButtonElement(videoData[field]);
            } else if (field === 'image') {
                elem = generateImageElement(videoData[field]);
            } else {
                elem = videoData[field] ? videoData[field] : ' - ';
            }
            elem = generateColumn(elem);
            newRow.appendChild(elem);
        });
        return newRow;
    }

    function generateButtonElement(videoId) {
        let newButton = document.createElement('button');
        newButton.innerHTML = 'Watch';
        newButton.onClick = () => window.location.href = `url/path/${id}`;
        return newButton;
    }

    function generateColumn(object) {
        let newColumn = document.createElement('td');
        if (typeof object === 'string') {
            newColumn.innerHTML = object;
        } else {
            newColumn.appendChild(object);
        }
        return newColumn;
    }

    function generateImageElement(source) {
        let newImage = document.createElement('img');
        newImage.src = source;
        return newImage;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

Error: Failed to clone an object in Electron due to an unhandled promise

I'm in need of assistance with sending files from the main directory to the renderer. Before proceeding, I attempted to check if it was functioning correctly by using console.log(files). However, this resulted in an error message. Can someone please p ...

Choosing between FOR JSON PATH and FOR JSON AUTO in SQL Server can have a significant

I'm encountering an issue in SQL Server with creating nested JSON structures. My goal is to generate an output that resembles the following: [ { "websiteURL": "www.example.edu", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf ...

Having trouble choosing an item from the Select2 drop-down menu

I have been developing an application that incorporates Select2 (version 3.5.1). The HTML used to create the dropdown / autocomplete field is as follows: <input id="mySelect" class="form-control" type="hidden"> The snippet above includes the form-c ...

By employing jQuery ajax and leaving out a value for the form action attribute

Recently, I designed an ajax sign-up form using jQuery that connects to a PHP backend. One question I have is whether it's wise to keep the form attribute action="" empty and let the ajax interface handle everything. Are there any potential downsides ...

Mapping a one-to-many relationship between Jersey web service and Hibernate

Encountering the 500 - Internal Server Error in POSTMAN while attempting to create a new user using Jersey rest service. Seeking guidance on properly loading and forming the JSON for hibernate one-to-many mappings. Utilizing jersey-media-moxy for JSON supp ...

Running multiple npm scripts on both Unix and Windows systems can be achieved by using the "npm

Is there a way for me to execute multiple npm scripts synchronously, one after another? Below are the npm scripts I have in my project, which includes both bower and npm packages: { "scripts": { "installnpm": "npm i", "installbower": "bower i", ...

Encountering the error message "Unable to retrieve resource: server returned a 404 status code (Not Found)" when trying to display an image

I am new to using React and I'm currently working on a Book project. However, I am facing an issue where the images of the books are not loading in the React app. Here is the directory tree: https://i.sstatic.net/T6ska.png Below is my app.jsx file: i ...

What is the process for creating custom styles for MUIV5 components?

I have incorporated Mui v5 components into my project and currently I am utilizing sx props to style all the MUI components. However, it is becoming cumbersome to add sx in every line for each component. Therefore, I am seeking alternative methods for styl ...

What sets apart .ejs from .html files?

In my Node Js project, all front end files are in .ejs format and call the server.js for backend work. 1) Is there additional functionality provided by ejs compared to html? 2) Does this pertain to expressJs functionality in Node? 3) Can I use angularJs ...

Extracting server error messages on the client side using Node.js

Before storing data in the database, my server performs validation checks. If it is unable to save the data into the database, an error message is sent. In my client-side application, how can I retrieve and display this error message? Below is the HTTP r ...

Utilize the nest function in D3 to organize flat data with a parent key into a hierarchical structure

I'm searching for an elegant and efficient solution to transform my input data into a hierarchical structure using d3.js nest operator. Here is an example of the input data: [ {id: 1, name: "Peter"}, {id: 2, name: "Paul", manager: 1}, {id: 3, name: " ...

Dealing with HTTP status codes in jQuery AJAX requests

Currently in the process of transitioning my scripts to jQuery. Here is snippet of my old JavaScript code: var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ActiveXObject ? new window.ActiveXObject("Microsoft.XMLHTTP") : false); reque ...

Disable the movement and dragging functionality of the scroll feature in Google Maps using React

I have a map.jsx file in my React application that contains the code below: import React from 'react'; import GoogleMapReact from 'google-map-react'; import './map.css'; const Map = ({ location, zoomLevel }) => ( <d ...

Having difficulty integrating framer-motion with react-router

I've been working on adding animations and smooth transitions to my app using Framer-motion, but I'm facing some challenges in getting it all to function properly. With react-router 6, my goal is to trigger exit animations on route sub-component ...

Different results and errors may occur in PHP files when using if conditions

Three queries are executed simultaneously using a single object $sql. However, only one record is displayed in the "Product" array out of four records, and the remaining three records are not displayed. Additionally, the percentage value is shown as null i ...

Tips on transitioning from solving problems in JavaScript to C# programming

Currently, I am working on a coding exercise that involves finding the sum of multiples of 3 and 5 below a given number. The task is to create a function called ThreeFiveMultiples(num) that will calculate this sum. For instance, if the input num is 10, th ...

Hover Effect Dilemma with Div Element

Although it may seem like an easy question, I have been struggling with it for a week. On my website at this link, there is a portfolio section where the image changes to a description when the mouse hovers over it... My goal is to invert this behavior so ...

Firefox throwing XML parsing error when SVG is encoded as data URI

Check out my codepen demo showcasing the issue: codepen.io/acusti/pen/mJmVRy Encountering an error when trying to load svg content in Firefox: XML Parsing Error: unclosed token Location: data:image/svg+xml;utf8,<svg%20viewBox='0%200%20120%2 ...

What are the top recommendations for implementing typography in SCSS?

As I ponder the best approach to take, I find myself torn between two options and wondering what the 'best practice' in this situation might be. My objective is to implement a selector that removes the standard global margin of 20px that I have ...