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:

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

The Implementation of Comet Programming

I'm interested in creating a web application similar to Google Docs where multiple users can edit and view changes in real-time. Would Comet Programming be the best approach for this? As a newcomer to Web Development, I'm currently learning Java ...

What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link. var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.37859 ...

Modifying button appearance upon clicking using JavaScript

JavaScript: const buttons = document.getElementsByClassName("togglebtn"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { this.classList.toggle("active"); } } html: <md-butt ...

Customize a theme component only when it is a child of another component

I am trying to customize the CSS of MuiButton only when it is nested inside a MuiDialog. https://i.stack.imgur.com/13doLm.png In regular CSS, you could achieve this with: .MuiDialog-root .MuiButton-root { border: 5px solid blue; } However, I am strug ...

Issues with the .change(function() JavaScript in Internet Explorer versions less than 9

I'm experiencing issues with this script in Internet Explorer versions below 9. Can someone please help me identify what is wrong with my script? Thank you. IE7 and IE8 are showing the following error: SCRIPT87: Invalid argument. Found ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

Guide to Spidermonkey Bytecode Documentation

I've been searching for a comprehensive guide to spidermonkey's bytecodes for some time now, or at least something that gives me an overview of their purpose. Does anyone know of a good resource for this? Thank you! ...

The Access-Control-Allow-Origin error is preventing the Angularjs post request from going through

I am encountering an issue with my index.html file that is sending a post request to localhost:3000/SetUser. The error I keep receiving states XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is p ...

An AJAX script for dynamically adding, modifying, and removing records from a database

How can I implement a functionality where by pressing "-" the vote is removed from the database, and when any other number is selected, the vote will be updated in the database with that value? The default value of the dropdown list is votacion.votCalific ...

The navbar does not dictate the views

Greetings lovely individuals I've been grappling with this issue for a while now and it seems I can't quite crack it on my own... I'm hopeful that you can assist me. My objective: A functioning navigation bar controlled by PHP in an MVC pat ...

Performing an AJAX request to send data containing special characters

What is the best way to send a large string with special characters like '%' and '&' to my PHP page using AJAX POST? In simple terms, how can I encode these characters in JavaScript and then decode them in PHP? ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Conceal an element within the initial row of the table

Below is the table structure: <table id="mytable"> <tr> <td>name</td> <td> <a id="button1" class="button">link</a> </td> </tr> <tr> <td>name2</td> ...

Avoiding layout shift when a button is clicked in React JS

I am working on a Drawer example and following the instructions provided at https://mui.com/material-ui/react-drawer/ Everything is functioning as expected, but I am encountering an issue where my content shifts to the right when the drawer opens, and ret ...

Implementing specific CSS styles for images that exceed a certain size limit

Currently, I am facing a dilemma as I work on developing a basic iPhone website that serves as a port for my blog. The main issue I am encountering is the need to add a border around images above a specific size and center them in order for the blog to hav ...

Automatically update certain attributes of an object with Spring MVC's auto-refresh feature

Currently, I have a table in JSP where I am populating all object attributes using Spring MVC. The backend is providing a list of DTO's which are then being added to the ModelView. In the JSP, we iterate through this DTO list and display it in the tab ...

Having trouble deleting the value and deselecting the checkbox item?

Feeling a bit confused about a coding issue I'm facing. The problem lies in the categories listed in my database, which I fetched and used to create a post. Now, I'm attempting to edit that post. The categories are in checkbox format, where check ...

Icons in Semantic-UI: Facing Difficulty in Accessing ("CORS Request Not HTTP"

Here's an example I'm working on: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Understanding - Main</title> <link rel="stylesheet" type="text/css" href="../semantic/dist/semanti ...