简体   繁体   中英

Edit the HTML table using Jquery( adding text boxes using buttons)

I am a beginner at jquery. I have created a table dynamically using javascript. I wanted to edit the table and also save it. I have put 2 buttons for each row. When I click the edit button i want to add text boxes to it and when I click the save button it should save it in the database. My Jquery code is not correct. I have used table id. It doesn't work. Please help. Thanks in advance

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="content">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>how to get data from ajax request in node js</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</head>


<body>
    <style>
td {
  pointer-events: none;
}

</style>
    <div class="container">

        <table class="table my-4" id="tableId">
<tbody id="myTable">
    
</tbody> 
        </table>
    </div>

    <script>
            
        var role =2;

        var permissions = {
                1: {
                    columns: [
                        "Id",
                        "firstName",
                        "lastName",
                        "email",
                        "dateofbirth",
                        "address",
                        "phoneNumber",
                        "feesPaid",
                        "password",
                        "actions"
                    ],
                },
                
                2: {
                    columns: ["Id", "firstName", "lastName", "address", "actions"],
                },

                3: {
                    columns: ["Id", "firstName", "email", "phoneNumber", "actions"],
                },
            };
createDynamicTable();
        let url = "http://localhost:3000/students";
        var myarray = [];

         fetch(url).then((data) => {

             return data.json();
        }).then((completedata) => {
             buildtable(completedata.data);
              var table = document.getElementById("myTable");
              var rows = table.rows.length; 
              console.log(rows);

         });

         

        function buildtable(data) {
var table = document.getElementById('myTable');   

            for (var i = 0; i < data.length; i++) {
                var row = `<tr>`;
             
            if (permissions[role].columns.includes("Id")) {
                    var id = `<td>${data[i].Id}</td>`
                    row = row + id;
                }
                if (permissions[role].columns.includes("firstName")) {
                    var firstName = `<td>${data[i].firstName}</td>`
                    var row = row + firstName;
                }
                if (permissions[role].columns.includes("lastName")) {
                    var lastName = `<td>${data[i].lastName}</td>`
                    var row = row + lastName;
                }
                if (permissions[role].columns.includes("email")) {
                    var email = `<td>${data[i].email}</td>`
                    var row = row + email;
                }
                if (permissions[role].columns.includes("dateofbirth")) {
                    var dateOfBirth = `<td>${data[i].dateofbirth}</td>`
                    var row = row + dateOfBirth;
                }
                if (permissions[role].columns.includes("address")) {
                    var address = `<td>${data[i].address}</td>`
                    var row = row + address;
                }
                if (permissions[role].columns.includes("phoneNumber")) {
                    var phoneNumber = `<td>${data[i].phoneNumber}</td>`
                    var row = row + phoneNumber;
                }
                if (permissions[role].columns.includes("feesPaid")) {
                    var feesPaid = `<td>${data[i].feesPaid}</td>`
                    var row = row + feesPaid;
                }
                if (permissions[role].columns.includes("password")) {
                    var password = `<td>${data[i].password}</td>`
                    var row = row + password;
                } 

             var closeRow =`</tr>`
             row = row + closeRow;
                table.innerHTML += row;
            }
let tr = document.querySelectorAll("tr:not(:first-child)");
          let button = document.createElement("button");
          button.className = "btn_buy";
            Array.from(tr).forEach(function (trArray) {
                                   

                let button = document.createElement("button");
                 td = document.createElement("td");
                button.innerText = "edit";
                button.className = "btn_buy";
                td.append(button);
                trArray.append(td);
                let button2 = document.createElement("button");
                let td2 = document.createElement("td");
                button2.innerText = "save";
                button2.className = "btn_buyd";
                td2.append(button2);
                trArray.append(td2);
            });
  table.innerHTML += row;
}
function createDynamicTable(){
    

     var table = document.getElementById('myTable');

     if(role == 1){
    var orderArrayHeader = permissions["1"].columns;
    
     }
     else if (role == 2){
            var orderArrayHeader = permissions["2"].columns;
            
     }
     else if (role == 3){
        var orderArrayHeader = permissions["3"].columns
        
     }
    var thead = document.createElement('thead');

    table.appendChild(thead);
    
    for (var i = 0; i < orderArrayHeader.length; i++) {
        thead.appendChild(document.createElement("th")).
            appendChild(document.createTextNode(orderArrayHeader[i]));
    }
}

            $("#tableId.cell").click(function (e) {
                console.log('1');
                if ($(this).find('input').length) {
                    return;
                }

                var input = $("<input type='text' size='5' />").val($(this).text());
                $(this).empty().append(input);
                $(this).find('input')
                    .focus(function (e) {
                        if ($(this).val() == '0.00' || $(this).val() == '0') { $(this).val(''); }
                    }).keydown(function (event) {
                        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 190 || event.keyCode == 13 ||
                            // Allow: Ctrl+A
                            (event.keyCode == 65 && event.ctrlKey === true) ||
                            // Allow: home, end, left, right
                            (event.keyCode >= 35 && event.keyCode <= 39)) {
                            // let it happen, don't do anything
                            return;
                        }
                        else {
                            // Ensure that it is a number and stop the keypress
                            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                                event.preventDefault();
                            }
                        }
                    }).blur(function (e) {
                        if ($(this).val() != "") {
                            if (!isNaN(parseFloat($(this).val()))) {
                                var val1 = parseFloat($(this).val()).toFixed(2);
                                $(this).val(val1);
                                $(this).parent('td').text(
                                    $(this).val()
                                );
                            }
                        }
                        else {
                            $(this).parent('td').text("0.00");
                        }
                    });
            });

            $(function () {
                $('table tr td').hover(function () {
                    $(this).css('background-color', '#FFFFB0');
                },
                    function () {
                        $(this).css('background-color', '#F4F4F4');
                    });
            });
        

Welcome to development. good choice.

i think of it as two version of each row. an editable version with form elements in the cells, or the view mode with labels or spans containing data.

Whether you switch out cell by cell horizontally or replace the whole row, you'll need two sets of buttons:

edit & delete // Save & discard

you pivot between the two as you go in and out of edit mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM