Home > Enterprise >  Delete button in For loop table content
Delete button in For loop table content

Time:10-26

I hope everyone is doing fine in this wreched day and age!

I'm having an issue completing a task given by my superior. Namely, I've created a table and completed sorting by rating and managed to make a working add content button. But I hit the wall with trying to add delete button next to every object in the table. Help would be more than welcome.

This is js. 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" },
 
];


//Toggle Sort

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;
            }
        }
    }
};

//Add content to the table
function addTableRow() {
    let table = document.getElementById('tableData');
    let txt = '';
    let movieNameInput = document.getElementById('movieName').value;
    let movieGenreInput = document.getElementById('movieGenre').value;
    let movieRatingInput = document.getElementById('movieRating').value;

    let row = table.insertRow();
    txt = txt   `<tr><td>${movieNameInput}</td><td>${movieGenreInput}</td><td>${movieRatingInput}</td></tr>`;
    row.innerHTML = txt;


}


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;
    background-color: rgb(250, 241, 231);
}

table {
    border-collapse: collapse;
    width: 50%;
    text-align: center;
    margin: 40px auto;
}

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>

<!--TABLE-->

<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="movieName"> 
        Genre : <input type="text" name="text" id="movieGenre"> 
        Rating : <input type="text" name="rating" id="movieRating">


        <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:

If I understood your question correctly, then you might want to create the buttons directly during the creation of the table. In the HTML you need to create another with an appropriate title, e.g. "actions"

Then you need to adapt the functions addTableRow and loadTableData where you add a after the last containing a button with e.g. an onclick event calling a function "deleteRow(i)" where i is equivalent to the id of the array element you are creating.

Then you change the element in both of these functions to also have an id="rowi" where "i" in "rowi" once again is the id of the corresponding array element in the list.

txt = txt   `<tr id="row` i `"><td>${movieData[i].name}</td><td>${movieData[i].genre}</td><td>${movieData[i].rating}</td><td><button value="Delete" onclick="deleteRow(` i `)"></tr>`;

Do not forget to adapt this line accordingly for the addTableRow function so that the i corresponds to the next id inserted into the table.

Lastly you create a function deleteRow(rowid) which deletes the whole where id is rowid.

function deleteRow(rowid) {
  document.getElementById(rowid).remove();
}

CodePudding user response:

From what I understood you need a delete button for every row of movies. If so, you need to create a button in the loadTableData() method itself.

And since you would be wanting to delete the movie altogether from the list on click of it, you'd need to send the id or in your case, the index of the movie along with it, like,

<td><button onclick="deleteRow(${i});">Delete</button></td>

and create a handler accordingly, like so,

function deleteRow(i) {
  movieData.splice(i, 1);
  loadTableData(movieData);
}

As you can see this works. But the loadTableData(movieData) function call at the end takes care of refreshing the UI, but it doesn't really consider the current sorted view. That I guess you should be able to figure out or handle as per your discretion.

'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" },
 
];


//Toggle Sort

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;
            }
        }
    }
};

//Add content to the table
function addTableRow() {
    let table = document.getElementById('tableData');
    let txt = '';
    let movieNameInput = document.getElementById('movieName').value;
    let movieGenreInput = document.getElementById('movieGenre').value;
    let movieRatingInput = document.getElementById('movieRating').value;

    let row = table.insertRow();
    txt = txt   `<tr><td>${movieNameInput}</td><td>${movieGenreInput}</td><td>${movieRatingInput}</td></tr>`;
    row.innerHTML = txt;


}

function deleteRow(i) {
  movieData.splice(i, 1);
  loadTableData(movieData);
}


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><td><button onclick="deleteRow(${i});">Delete</button></td></tr>`;
    }
    tableBody.innerHTML = txt
}
body {
    background-color: #f2f2f2f2;
    color: black;
    font-weight: 500;
    background-color: rgb(250, 241, 231);
}

table {
    border-collapse: collapse;
    width: 50%;
    text-align: center;
    margin: 40px auto;
}

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>

<!--TABLE-->

<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>
                    <th class="name">Action</th>
                    
                </tr>
            </thead>

            <tbody id="tableData">

            </tbody>

        </table>
    </div>

    <br>


    <!--ADD/REMOVE BUTTON-->
   
   <div class="addremove">

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


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

    </div>

    </div>







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

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

Happy coding!

CodePudding user response:

Like this :

enter image description here

Add your HTML code (table)

  • Related