Home > OS >  Button to add content to an JSON object array table
Button to add content to an JSON object array table

Time:10-22

I'm, a 7 days javascript newbie and I got a task to fulfill.

I had to enlist JSON file with 50-ish objects into the table and make it sorable by click, which I did. Now I have to implement Add button, which will create another row. I did something, but it's not showing me any results. Here is my code:

function addTableRow() {
    let table = document.getElementById("tableObjects");
    newRow = table.insertRow(cars.length),
        cell1 = newRow.insertCell(0),
        cell2 = newRow.insertCell(1),
        cell3 = newRow.insertCell(2),
        ntxt = document.getElementById('ntxt'),
        gtxt = document.getElementById('gtxt'),
        rtxt = document.getElementById('rtxt');

    cell1.innerHTML = ntxt;
    cell2.innerHTML = gtxt;
    cell3.innerHTML = rtxt;`
}

What exactly am I doing wrong?

CodePudding user response:

All your errors are here:

let table = document.getElementById("tableObjects"); // <-- Error, replace with comma
newRow = table.insertRow(cars.length),
    cell1 = newRow.insertCell(0),
    cell2 = newRow.insertCell(1),
    cell3 = newRow.insertCell(2),
    ntxt = document.getElementById('ntxt'),  // <-- You want the value ".value"
    gtxt = document.getElementById('gtxt'),  // <-- You want the value ".value"
    rtxt = document.getElementById('rtxt');  // <-- You want the value ".value" and the id is rtext not rtxt

This is my correction

let table = document.getElementById("tableData"), 
    newRow = table.insertRow(table.length),
    cell1 = newRow.insertCell(0),
    cell2 = newRow.insertCell(1),
    cell3 = newRow.insertCell(2),
    ntxt = document.getElementById('ntxt').value,
    gtxt = document.getElementById('gtxt').value,
    rtxt = document.getElementById('rtext').value;

And the whole working code:

'use strict'

let movieData = [{ "id": 1, "name": "Network", "genre": "Comedy|Drama", "rating": "68.22" },
    { "id": 2, "name": "Kommissarie Späck", "genre": "Comedy", "rating": "30.65" },
    { "id": 3, "name": "Pirate, The", "genre": "Adventure|Comedy|Musical|Romance", "rating": "98.22" },
    { "id": 4, "name": "Mary and Martha", "genre": "Drama", "rating": "11.15" },
    { "id": 5, "name": "Four Days in September (O Que É Isso, Companheiro?)", "genre": "Drama", "rating": "20.35" },
    { "id": 6, "name": "Sibling Rivalry", "genre": "Comedy", "rating": "5.91" },
    { "id": 7, "name": "Alice in Wonderland", "genre": "Adventure|Children|Fantasy", "rating": "52.69" },
    { "id": 8, "name": "Dead Weekend", "genre": "Comedy|Sci-Fi", "rating": "30.84" },
    { "id": 9, "name": "Top Hat", "genre": "Comedy|Musical|Romance", "rating": "60.06" },
    { "id": 10, "name": "Cleopatra", "genre": "Drama|Romance|War", "rating": "65.39" },
    { "id": 11, "name": "For All Mankind", "genre": "Documentary", "rating": "73.24" },
    { "id": 12, "name": "Messiah of Evil", "genre": "Horror", "rating": "28.9" },
    { "id": 13, "name": "Princess and the Pirate, The", "genre": "Adventure|Comedy|Romance", "rating": "20.41" },
    { "id": 14, "name": "Restrepo", "genre": "Documentary|War", "rating": "71.18" },
    { "id": 15, "name": "Return to the Blue Lagoon", "genre": "Adventure|Romance", "rating": "67.92" },
    { "id": 16, "name": "Convoy", "genre": "Action|Comedy|Drama", "rating": "22.53" },
    { "id": 17, "name": "Perfect", "genre": "Drama|Romance", "rating": "86.25" },
    { "id": 18, "name": "Son of Babylon (Syn Babilonu)", "genre": "Drama", "rating": "26.54" },
    { "id": 19, "name": "Heaven and Earth (Ten to Chi to)", "genre": "Action|Adventure|Drama|War", "rating": "69.39" },
    { "id": 20, "name": "Carcasses", "genre": "Documentary", "rating": "3.72" },
    { "id": 21, "name": "Repentance", "genre": "Drama|Horror|Thriller", "rating": "55.21" },
    { "id": 22, "name": "Loose Change: Second Edition", "genre": "Documentary|Mystery", "rating": "72.22" },
    { "id": 23, "name": "Resurrection Man", "genre": "Drama|Thriller", "rating": "74.68" },
    { "id": 24, "name": "Green Card", "genre": "Comedy|Drama|Romance", "rating": "35.28" },
    { "id": 25, "name": "Micki   Maude", "genre": "Comedy", "rating": "2.02" },
    { "id": 26, "name": "Rover, The", "genre": "Crime|Drama", "rating": "18.73" },
    { "id": 27, "name": "Dark Horse (Voksne mennesker)", "genre": "Comedy|Drama|Romance", "rating": "28.19" },
    { "id": 28, "name": "Street Thief", "genre": "Crime|Documentary", "rating": "67.11" },
    { "id": 29, "name": "Woman In Berlin, A (Anonyma - Eine Frau in Berlin)", "genre": "Drama|War", "rating": "13.85" },
    { "id": 30, "name": "Expendables, The", "genre": "Action|Adventure|Thriller", "rating": "92.78" },
    { "id": 31, "name": "American Haunting, An", "genre": "Drama|Horror|Mystery|Thriller", "rating": "54.56" },
    { "id": 32, "name": "Charlotte Gray", "genre": "Drama|Romance", "rating": "2.79" },
    { "id": 33, "name": "Just Bea (Bare Bea)", "genre": "Drama", "rating": "65.83" },
    { "id": 34, "name": "Land Before Time, The", "genre": "Adventure|Animation|Children|Fantasy", "rating": "36.84" },
    { "id": 35, "name": "Mists of Avalon, The", "genre": "Drama|Fantasy", "rating": "25.29" },
    { "id": 36, "name": "Slaughter of the Innocents", "genre": "Crime|Horror|Mystery|Thriller", "rating": "51.11" },
    { "id": 37, "name": "Good Fairy, The", "genre": "Comedy|Romance", "rating": "7.09" },
    { "id": 38, "name": "G.O.R.A.", "genre": "Adventure|Comedy|Sci-Fi", "rating": "54.07" },
    { "id": 39, "name": "Anthony Zimmer", "genre": "Crime|Drama|Romance|Thriller", "rating": "86.28" },
    { "id": 40, "name": "Men in Black (a.k.a. MIB)", "genre": "Action|Comedy|Sci-Fi", "rating": "34.52" },
    { "id": 41, "name": "Slingshot, The (Kådisbellan)", "genre": "Comedy|Drama", "rating": "6.89" },

];




function sortTable(n) {
    let table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
    table = document.getElementById("tableData");
    switching = true;
    dir = 'asc';
    while (switching) {
        switching = false;
        rows = table.rows;
        for (i = 0; i < (movieData.length - 1); i  ) {
            shouldSwitch = false;
            x = rows[i].getElementsByTagName('td')[n];
            y = rows[i   1].getElementsByTagName('td')[n];
            if (dir == 'asc') {
                if (parseFloat(x.innerHTML) > parseFloat(y.innerHTML)) {
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == 'desc') {
                if (parseFloat(x.innerHTML) < parseFloat(y.innerHTML)) {
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if (shouldSwitch) {
            rows[i].parentNode.insertBefore(rows[i   1], rows[i]);
            switching = true;
            switchcount  ;
        } else {
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
};



function addTableRow() {
    let table = document.getElementById("tableData"),
        newRow = table.insertRow(table.length),
        cell1 = newRow.insertCell(0),
        cell2 = newRow.insertCell(1),
        cell3 = newRow.insertCell(2),
        ntxt = document.getElementById('ntxt').value,
        gtxt = document.getElementById('gtxt').value,
        rtxt = document.getElementById('rtext').value;

    cell1.innerHTML = ntxt;
    cell2.innerHTML = gtxt;
    cell3.innerHTML = rtxt;

};

window.onload = () => {
    loadTableData(movieData);
}



function loadTableData(movieData) {
    let tableBody = document.getElementById('tableData');
    let txt = '';
    for (let i = 0; i < movieData.length; i  ) {
        txt = txt   `<tr><td>${movieData[i].name}</td><td>${movieData[i].genre}</td><td>${movieData[i].rating}</td></tr>`;
    }
    tableBody.innerHTML = txt
}
body {
    background-color: #f2f2f2f2;
    color: black;
    font-weight: 500;
}

table {
    border-collapse: collapse;
    width: 100%;
    text-align: center;
}

tr,
th {
    border: 1px solid #cccccc;
    padding: 8px;
    font-size: 16px Z;
}

th {
    font-weight: bold;
    text-transform: uppercase;
    color: bisque;
    background-color: #444
}

tr:nth-child(even) {
    background: rgba(15, 85, 6, 0.438);
}

tr:hover {
    color: whitesmoke;
    background-color: rgba(82, 79, 78, 0.568);
    transition: ease-in-out .5s;
}

.name {
    background: #444;
}

.genre {
    background-color: rgba(240, 101, 50, 0.411)
}

.toggler {
    cursor: pointer;
    -webkit-user-select: none;
    user-select: none;
    background-color: rgba(245, 62, 6, 0.658);
}

.addremove {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 15px;
    color: coral;
    font-weight: 900;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Tabela</title>

</head>

<!--TABELA-->

<body>
    <div class="container">
        <table class="table">
            <thead>
                <tr>
                    <th class="name">Name</th>
                    <th class="genre">Genre</th>
                    <th class="toggler" onclick="sortTable(2)">Rating</th>
                </tr>
            </thead>

            <tbody id="tableData">

            </tbody>

        </table>
    </div>

    <br>


    <!--ADD/REMOVE BUTTON-->
    <div class="addremove">
        Name : <input type="text" name="text" id="ntxt"> 
        Genre : <input type="text" name="text" id="gtxt"> 
        Rating : <input type="number" name="rating" id="rtext">

        
        <button onclick="addTableRow();">Add</button>

    </div>

    </div>







    <script src="app.js"></script>
</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I focused on solving your particular issue when adding a new item.

First of all the name of the ids in the inputs can be more descriptive and intuitive like so.

Name : <input type="text" name="text" id="movieName">
Genre : <input type="text" name="text" id="movieGenre">
Rating : <input type="number" name="rating" id="movieRating">

Then in your addTableRow function here is the fix.

function addTableRow() {
  const table = document.getElementById('tableData'),
    newRow = table.insertRow(table.length),
    cell1 = newRow.insertCell(0),
    cell2 = newRow.insertCell(1),
    cell3 = newRow.insertCell(2),
    // Renamed inputs with a meaningful and descriptive name
    movieNameInput = document.getElementById('movieName'),
    movieGenreInput = document.getElementById('movieGenre'),
    movieRatingInput = document.getElementById('movieRating')

  // You were passing the HTMLElement object and not it's value.
  // Now we are passing the value of every input Element. 
  cell1.innerHTML = movieNameInput.value
  cell2.innerHTML = movieGenreInput.value
  cell3.innerHTML = movieRatingInput.value
}

That should do the trick, hopefully this was helpful.

  • Related