Is there a way to make a table row clickable? I tried finding solutions online, but none of them seemed to work for me

Having trouble opening a new page when tapping on a cell (TR) using Javascript. Despite trying various online tutorials, I still can't get it to work properly. Any assistance would be greatly appreciated. Thank you.

Below is the code snippet:

function generateTableBirre() 
{
    var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
    var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];

    var table = document.createElement("table");
    table.border = "1";
    table.className = "Birre";
    table.cellSpacing = 20;

    for (var i = 0; i < birre.length; i++) {
        var row = table.insertRow(-1);
        var cell = row.insertCell(-1);

        var generalDiv = document.createElement("div");
        generalDiv.className = "General-Div";

        var a = document.createElement('a');
        a.href = "Antipasti.html";
        a.appendChild(cell);
        cell.appendChild(a);

        var div = document.createElement("div");
        div.id = "div-nome-prezzo-birre";

        var nameprezzo = document.createElement("p");
        nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
        nameprezzo.id = "nome-prezzo-birre";

        div.appendChild(nameprezzo);

        var image = document.createElement("img");
        image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
        image.id = "image-bibite";

        generalDiv.appendChild(div);
        generalDiv.appendChild(image);

        cell.appendChild(generalDiv);
    }

    var dvTable = document.getElementById("dvTable");
    dvTable.innerHTML = "";
    dvTable.appendChild(table);
}

If you need to view the table, click on the following image: https://i.sstatic.net/zattp.png

Answer №1

This JavaScript code creates a table with 2 cells per row. The first cell contains a div with a text paragraph, while the second cell contains a div with an anchor and an image.

Note: Each id must be unique, so any duplicate ids have been removed. Additional selectors can be added using classList.add("...")

In the CSS, you can customize the image width, font, color, etc. For example:

#dvTable img { max-width: 250px; height: auto; border: 0; }

    function generateTableBirre() {
      // array of beer records
      var beers = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
      var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
      // create table
      var table = document.createElement('table');
      table.classList.add("Beers");
      table.setAttribute('border', '1');
      table.setAttribute('cellspacing', '20');
      // loop through array and create rows
      for (var i = 0; i < beers.length; i++) {
        var row = document.createElement('tr');
        // loop to create two cells per row
        for (var j = 0; j < 2; j++) {
          var cell = document.createElement('td');
          // add inner div to each cell
          var div = document.createElement("div");
          div.classList.add("General-Div");
          cell.appendChild(div);
          // different content in cell 0 and cell 1
          if (j == 0) {
            // cell 0 has a paragraph
            var par = document.createElement("p");
            par.innerHTML = beers[i] + ' - ' + price[i];
            div.appendChild(par);
          } else {
            // cell 1 has an image inside an anchor
            var anch = document.createElement('a');
            anch.setAttribute('href', 'Antipasti.html');
            div.appendChild(anch);
            var img = document.createElement("img");
            img.setAttribute('src', 'https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png');
            anch.appendChild(img);
          }
          row.appendChild(cell);
        }
        table.appendChild(row);
      }
      // append table to id=dvTable
      var dvTable = document.getElementById("dvTable");
      dvTable.innerHTML = "";
      dvTable.appendChild(table);
    }
    generateTableBirre();
<div id="dvTable">
</div>

Answer №2

give this a shot,

function createBeerTable() {
//Build an array of different beer types.
var beers = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var prices = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];

//Create an HTML table element.
var table = document.createElement("table");
table.border = "1";
table.className = "Beers";
table.cellSpacing = 20;

//Populate the table with data rows.
for (var i = 0; i < beers.length; i++) {

    var row = document.createElement("tr");
    table.appendChild(row);
    var cell = document.createElement("td");
    var generalDiv = document.createElement("div");
    generalDiv.className = "General-Div";

    // Create a link
    var link = document.createElement('a');
    link.href = "Antipasti.html";
    link.appendChild(cell);
    row.appendChild(link);

        var div = document.createElement("div");
        div.id = "beer-name-price-div";

            var namePrice = document.createElement("p");
            namePrice.innerHTML = beers[i] + ' - ' + prices[i];
            namePrice.id = "beer-name-price";

        div.appendChild(namePrice);

    var image = document.createElement("img");
    image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
    image.id = "beer-image";

    generalDiv.appendChild(div);
    generalDiv.appendChild(image);

    cell.appendChild(generalDiv);
}
var beerTableContainer = document.getElementById("beerTableContainer");
beerTableContainer.innerHTML = "";
beerTableContainer.appendChild(table);
}

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

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

I have successfully established a new channel, but I am having difficulty retrieving the unique identifier for it

After using the provided code to create a channel, I'm having trouble locating the channel ID needed for the next step in my function. This function is meant to move to a specific category and send a message to it. const buyid = generateID message. ...

As the user scrolls down, the navigation becomes obscured by the content

Whenever I scroll down on my website at Bradly Spicer, the navigation menu extends and ends up falling behind the content. This is the script I am using: .menu { position: relative; z-index:9999; } .post { background: #fff; border: 1px solid #ddd; font- ...

more concise jQuery script

Currently, I am a beginner in jquery and still in the learning phase. Although my existing code is functional and achieving the desired outcome, it feels lengthy and inefficient. I am seeking a way to streamline it and make it more dynamic. Specifically, t ...

Using AJAX to remove data from a database

My PHP code snippet is displayed below: AjaxServer.php include '../include/connection.php'; // Check for the prediction if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){ $id = $_POST["id"]; $table = $_POST["table"]; ...

Arranging the columns of a matrix

My dilemma involves a matrix (or multidimensional array) filled with non-unique values, similar to this example: var matrix = [ [1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4] ] I am in need ...

Create a basic single page application with Node.js and Express

Currently, I am working on developing a web application utilizing Node.js for the Back End and HTML/CSS/JS for the Front End. My goal is to create a single page app using the Express framework. I am interested in building a single page application with ju ...

Exploring Vue.js: Navigating Through an Array of Images Nested Within Another Array

I am looking to showcase images stored in an array called "image" within another array named product. Essentially, if a product has an array of 3 images, I want to display all 3 images, and so on. Here is the code snippet: <template> <div c ...

The JavaScript alert box cannot retrieve data from the PHP parent page

What am I missing? Here is the JavaScript code snippet: <script language="javascript"> function openPopup(url) { window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=n ...

Tips for building an API using an app router in Next.js

After setting up my new project and using the app router as recommended in the latest version of Next.js, I am now looking to create an API. How can I go about creating and utilizing this API within my page app/user/page.tsx? I have already created an API ...

Traversing an array in Javascript by iterating through its elements

So I have an array called var myImages = [];. After pushing items into it and using console.log(), I see the following: ["01_img"] ["02_img"] ["03_img"] ["04_img"] ["05_img"] When I click on something, I want to change the background of a div to display ...

Finding the class name of the parent div: A simple guide

Within a maze of nested divs, there lies a checkbox waiting to be deciphered. When the OnChange event triggers, I aim to unveil the hidden class name of the parent div/container div known as pan-box placeholder. The HTML journey begins with this structure ...

What is the proper way to include "arr[i]" within a for loop?

How can I include "arr[i].length" in my FOR LOOP? Using arr[0].length works correctly, but when using just "i" it throws an error. My goal is to iterate through a 2D array. function calculateSum(arr) { var total = 0; for (let i = 0; i < arr[i] ...

Send back a JsonResult containing a collection of objects from an MVC controller

In my MVC controller, I have a straightforward method: [HttpPost] public JsonResult GetAreasForCompany(int companyId) { var areas = context.Areas.Where(x => x.Company.CompanyId == companyId).ToList(); return Json(areas); } Here is the structure ...

Oops! Looks like there's a hiccup with the express-validator plugin as the validation fails due to req.checkBody not being recognized as

Currently, I am setting up a post route to handle a submit request. The code snippet provided is from my user.js route: var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multe ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

The jQuery .load() function does not seem to be functioning properly on secure HTTPS connections

After implementing an SSL certificate through Cloudflare on my website, I encountered an issue where a specific function returned an error code 0 and failed to load the URL content. How can I resolve this issue? $(function () { EnderReact(); }); functi ...

Encountered an issue with reading the property 'drop' from an undefined source during a straightforward migration

I recently started using the migrate-mongo library and encountered an issue during a simple migration process to create a view. Despite success in migrating up, I faced an error when attempting to migrate down. ERROR: Could not migrate down 20220620114132 ...

Testing for ajax failure using Q-Unit in a unit test

While utilizing jQuery's $.when method to manage ajax callbacks, I am also implementing mockjax for simulating various responses in my unit tests. One of these responses results in a status error of 500. Unfortunately, when catching this error using Q ...

changing tooltip color in bootstrap based on the parent element

Is there a way to adjust the bootstrap tooltip background-color based on the container? For example, my header has a white background and my footer is black. #header .tooltip-inner{ background-color:fade(@grayWhite,80); } #footer .tooltip-inner{ backgro ...