js+Html to realize table editable operation

js+Html to realize table editable operation

This article shares the specific code of js+Html to realize the editable operation of the table for your reference. The specific content is as follows

Function description: Click the page to make the cell td editable. After entering the content, when the cell loses focus, the entered content is saved.
Click Add Row to add a row at the end of the table; click Delete Row to delete the last row in the table.

<html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
    <title>Edit table data</title>  
    <style type="text/css">  
    <!--  
    body,div,p,ul,li,font,span,td,th{  
    font-size:10pt;  
    line-height:155%;  
    }  
    table{  
    border-top-width: 1px;  
    border-right-width: 1px;  
    border-bottom-width: 0px;  
    border-left-width: 1px;  
    border-top-style: solid;  
    border-right-style: solid;  
    border-bottom-style: none;  
    border-left-style: solid;  
    border-top-color: #CCCCCC;  
    border-right-color: #CCCCCC;  
    border-bottom-color: #CCCCCC;  
    border-left-color: #CCCCCC;  
    }  
    td{  
    border-bottom-width: 1px;  
    border-bottom-style: solid;  
    border-bottom-color: #CCCCCC;  
    }  
    .EditCell_TextBox {  
    width: 90%;  
    border:1px solid #0099CC;  
    }  
    .EditCell_DropDownList {  
    width: 90%;  
    }  
    -->  
    </style>  
    <script>
        /** 
    * JS implements editable tables * Usage: EditTables(tb1,tb2,tb2,......); 
    **/  
      
    //Set multiple tables to edit function EditTables(){  
    for(var i=0;i<arguments.length;i++){  
       SetTableCanEdit(arguments[i]);  
    }  
    }  
      
    //Set the table to be editable function SetTableCanEdit(table){  
    for(var i=1; i<table.rows.length;i++){  
       SetRowCanEdit(table.rows[i]);  
    }  
    }  
      
    function SetRowCanEdit(row){  
    for(var j=0;j<row.cells.length; j++){  
      
       //If the current cell specifies the edit type, editing is allowed var editType = row.cells[j].getAttribute("EditType");  
       if(!editType){  
        //If the current cell is not specified, check whether the current column specifies editType = row.parentNode.rows[0].cells[j].getAttribute("EditType");  
       }  
       if(editType){  
        row.cells[j].onclick = function (){  
         EditCell(this);  
        }  
       }  
    }  
      
    }  
      
    //Set the specified cell to editable function EditCell(element, editType){  
      
    var editType = element.getAttribute("EditType");  
    if(!editType){  
       //If the current cell is not specified, check whether the current column specifies editType = element.parentNode.parentNode.rows[0].cells[element.cellIndex].getAttribute("EditType");  
    }  
      
    switch(editType){  
       case "TextBox":  
        CreateTextBox(element, element.innerHTML);  
        break;  
       case "DropDownList":  
        CreateDropDownList(element);  
        break;  
       default:  
        break;  
    }  
    }  
      
    //Create an editable input box for the cell function CreateTextBox(element, value){  
    // Check the edit state, if it is already in edit state, skip var editState = element.getAttribute("EditState");  
    if(editState != "true"){  
       //Create a text box var textBox = document.createElement("INPUT");  
       textBox.type = "text";  
       textBox.className="EditCell_TextBox";  
        
        
       //Set the current value of the text box if (! value) {  
        value = element.getAttribute("Value");  
       }    
       textBox.value = value;  
        
       //Set the text box's focus loss event textBox.onblur = function () {  
        CancelEditCell(this.parentNode, this.value);  
       }  
       //Add a text box to the current cell ClearChild(element);  
       element.appendChild(textBox);  
       textBox.focus();  
       textBox.select();  
        
       //Change the state variable element.setAttribute("EditState", "true");  
       element.parentNode.parentNode.setAttribute("CurrentRow", element.parentNode.rowIndex);  
    }  
      
    }  
      
      
    //Create a selection box for the cell function CreateDropDownList(element, value){  
    // Check the edit state, if it is already in edit state, skip var editState = element.getAttribute("EditState");  
    if(editState != "true"){  
       //Create the lower frame var downList = document.createElement("Select");  
       downList.className="EditCell_DropDownList";  
        
       //Add list items var items = element.getAttribute("DataItems");  
       if(!items){  
        items = element.parentNode.parentNode.rows[0].cells[element.cellIndex].getAttribute("DataItems");  
       }  
        
       if(items){  
        items = eval("[" + items + "]");  
        for(var i=0; i<items.length; i++){  
         var oOption = document.createElement("OPTION");  
         oOption.text = items[i].text;  
         oOption.value = items[i].value;  
         downList.options.add(oOption);  
        }  
       }  
        
       //Set the current value of the list if (! value) {  
        value = element.getAttribute("Value");  
       }  
       downList.value = value;  
      
       //Set the focus loss event of the next frame downList.onblur = function (){  
        CancelEditCell(this.parentNode, this.value, this.options[this.selectedIndex].text);  
       }  
        
       //Add a lower frame to the current cell ClearChild(element);  
       element.appendChild(downList);  
       downList.focus();  
        
       //Record state changes element.setAttribute("EditState", "true");  
       element.parentNode.parentNode.setAttribute("LastEditRow", element.parentNode.rowIndex);  
    }  
      
    }  
      
      
    //Cancel cell editing function CancelEditCell(element, value, text){  
    element.setAttribute("Value", value);  
    if(text){  
       element.innerHTML = text;  
    }else{  
       element.innerHTML = value;  
    }  
    element.setAttribute("EditState", "false");  
      
    //Check if there is a formula calculation CheckExpression(element.parentNode);  
    }  
      
    // Clear all child nodes of the specified object function ClearChild(element) {  
    element.innerHTML = "";  
    }  
      
    //Add row function AddRow(table, index){  
    var lastRow = table.rows[table.rows.length-1];  
    var newRow = lastRow.cloneNode(true);  
    //To calculate the serial number of the newly added row, you need to import the jQuery jar package var startIndex = $.inArray(lastRow,table.rows);
    var endIndex = table.rows; 
    table.tBodies[0].appendChild(newRow);  
    newRow.cells[0].innerHTML=endIndex-startIndex;
    SetRowCanEdit(newRow);  
    return newRow;  
      
    }  
      
      
    //Delete row function DeleteRow(table, index){  
    for(var i=table.rows.length - 1; i>0;i--){  
       var chkOrder = table.rows[i].cells[0].firstChild;  
       if(chkOrder){  
        if(chkOrder.type = "CHECKBOX"){  
         if(chkOrder.checked){  
          //Execute deletion table.deleteRow(i);  
         }  
        }  
       }  
    }  
    }  
      
    //Extract the value of the table, JSON format function GetTableData(table){  
    var tableData = new Array();  
    alert("Number of rows: " + table.rows.length);  
    for(var i=1; i<table.rows.length;i++){  
       tableData.push(GetRowData(tabProduct.rows[i]));  
    }  
      
    return tableData;  
      
    }  
    //Extract the data of the specified row in JSON format function GetRowData(row){  
    var rowData = {};  
    for(var j=0;j<row.cells.length; j++){  
       name = row.parentNode.rows[0].cells[j].getAttribute("Name");  
       if(name){  
        var value = row.cells[j].getAttribute("Value");  
        if(!value){  
         value = row.cells[j].innerHTML;  
        }  
         
        rowData[name] = value;  
       }  
    }  
    //alert("ProductName:" + rowData.ProductName);  
    //Or like this: alert("ProductName:" + rowData["ProductName"]);  
    return rowData;  
      
    }  
      
    // Check the fields that need to be run in the current data row function CheckExpression(row){  
    for(var j=0;j<row.cells.length; j++){  
       expn = row.parentNode.rows[0].cells[j].getAttribute("Expression");  
       //If the formula is specified, calculation is required if (expn) {  
        var result = Expression(row,expn);  
        var format = row.parentNode.rows[0].cells[j].getAttribute("Format");  
        if(format){  
         //If the format is specified, format the text value row.cells[j].innerHTML = formatNumber(Expression(row,expn), format);  
        }else{  
         row.cells[j].innerHTML = Expression(row,expn);  
        }  
       }  
        
    }  
    }  
      
    //Calculate the fields that need to be calculated function Expression(row, expn){  
    var rowData = GetRowData(row);  
    //Loop value calculation for(var j=0;j<row.cells.length; j++){  
       name = row.parentNode.rows[0].cells[j].getAttribute("Name");  
       if(name){  
        var reg = new RegExp(name, "i");  
        expn = expn.replace(reg, rowData[name].replace(/\,/g, ""));  
       }  
    }  
    return eval(expn);  
    }  
      
    ///  
    /** 
    * Formatting number display mode * Usage * formatNumber(12345.999,'#,##0.00'); 
    * formatNumber(12345.999,'#,##0.##'); 
    * formatNumber(123,'000000'); 
    * @param num 
    * @param pattern 
    */  
    /* The following is an example formatNumber('','')=0 
    formatNumber(123456789012.129,null)=123456789012 
    formatNumber(null,null)=0 
    formatNumber(123456789012.129,'#,##0.00')=123,456,789,012.12 
    formatNumber(123456789012.129,'#,##0.##')=123,456,789,012.12 
    formatNumber(123456789012.129,'#0.00')=123,456,789,012.12 
    formatNumber(123456789012.129,'#0.##')=123,456,789,012.12 
    formatNumber(12.129,'0.00')=12.12 
    formatNumber(12.129,'0.##')=12.12 
    formatNumber(12,'00000')=00012 
    formatNumber(12,'#.##')=12 
    formatNumber(12,'#.00')=12.00 
    formatNumber(0,'#.##')=0 
    */  
    function formatNumber(num,pattern){    
    var strarr = num?num.toString().split('.'):['0'];    
    var fmtarr = pattern?pattern.split('.'):[''];    
    var retstr='';    
        
    // integer part var str = strarr[0];    
    var fmt = fmtarr[0];    
    var i = str.length-1;      
    var comma = false;    
    for(var f=fmt.length-1;f>=0;f--){    
        switch(fmt.substr(f,1)){    
          case '#':    
            if(i>=0 ) retstr = str.substr(i--,1) + retstr;    
            break;    
          case '0':    
            if(i>=0) retstr = str.substr(i--,1) + retstr;    
            else retstr = '0' + retstr;    
            break;    
          case ',':    
            comma = true;    
            retstr=','+retstr;    
            break;    
        }    
    }    
    if(i>=0){    
        if(comma){    
          var l = str.length;    
          for(;i>=0;i--){    
            retstr = str.substr(i,1) + retstr;    
            if(i>0 && ((li)%3)==0) retstr = ',' + retstr;     
          }    
        }    
        else retstr = str.substr(0,i+1) + retstr;    
    }    
        
    retstr = retstr+'.';    
    // Process the decimal part str=strarr.length>1?strarr[1]:'';    
    fmt=fmtarr.length>1?fmtarr[1]:'';    
    i=0;    
    for(var f=0;f<fmt.length;f++){    
        switch(fmt.substr(f,1)){    
          case '#':    
            if(i<str.length) retstr+=str.substr(i++,1);    
            break;    
          case '0':    
            if(i<str.length) retstr+= str.substr(i++,1);    
            else retstr+='0';    
            break;    
        }    
    }    
    return retstr.replace(/^,+/,'').replace(/\.$/,'');    
    }  
    </script>
    </head>  
      
    <body>  
    <form id="form1" name="form1" method="post" action="">  
    <h3>Editable table</h3>  
    <table width="698" border="0" cellpadding="0" cellspacing="0" id="tabProduct">  
        <tr>  
          <td width="32" align="center" bgcolor="#EFEFEF" Name="Num"><input type="checkbox" name="checkbox" value="checkbox" /></td>  
          <td width="186" bgcolor="#EFEFEF" Name="Num" EditType="TextBox">Serial number</td>  
          <td width="152" bgcolor="#EFEFEF" Name="ProductName" EditType="DropDownList" DataItems="{text:'A',value:'a'},{text:'B',value:'b'},{text:'C',value:'c'},{text:'D',value:'d'}">Product Name</td>  
          <td width="103" bgcolor="#EFEFEF" Name="Amount" EditType="TextBox">Quantity</td>  
          <td width="103" bgcolor="#EFEFEF" Name="Price" EditType="TextBox">Unit Price</td>  
          <td width="120" bgcolor="#EFEFEF" Name="SumMoney" Expression="Amount*Price" Format="#,###.00">Total</td>  
        </tr>  
        <tr>  
          <td align="center" bgcolor="#FFFFFF"><input type="checkbox" name="checkbox2" value="checkbox" /></td>  
          <td bgcolor="#FFFFFF">1</td>  
          <td bgcolor="#FFFFFF" Value="c">C</td>  
          <td bgcolor="#FFFFFF">0</td>  
          <td bgcolor="#FFFFFF">0</td>  
          <td bgcolor="#FFFFFF">0</td>  
        </tr>  
        <tr>  
          <td align="center" bgcolor="#FFFFFF"><input type="checkbox" name="checkbox22" value="checkbox" /></td>  
          <td bgcolor="#FFFFFF">2</td>  
          <td bgcolor="#FFFFFF" Value="d">D</td>  
          <td bgcolor="#FFFFFF">0</td>  
          <td bgcolor="#FFFFFF">0</td>  
          <td bgcolor="#FFFFFF">0</td>  
        </tr>  
    </table>  
      
    <br />  
    <input type="button" name="Submit" value="Add" onclick="AddRow(document.getElementById('tabProduct'),1)" />  
    <input type="button" name="Submit2" value="Delete" onclick="DeleteRow(document.getElementById('tabProduct'),1)" />  
    <input type="button" name="Submit22" value="Reset" onclick="window.location.reload()" />  
    <input type="submit" name="Submit3" value="Submit" onclick="GetTableData(document.getElementById('tabProduct'));return false;" />  
    </form>  
      
    <script language="javascript" src="GridEdit.js"></script>  
    <script language="javascript">  
    var tabProduct = document.getElementById("tabProduct");  
      
    // Set the table to be editable // You can set multiple at a time, for example: EditTables(tb1,tb2,tb2,......)  
    EditTables(tabProduct);  
      
      
    </script>  
    </body>  
</html>

The effect is as follows:

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue.js implements editable table
  • AngularJS implements table table td cell click to change input box/editable state example
  • Example of getting content and filling in the form when clicking on a row of the edit table in vuejs+element UI
  • Using JavaScript to implement a table editor (example explanation)
  • jQuery implements editable tables and generates json results (example code)
  • JS table component BootstrapTable inline editing solution x-editable
  • JavaScript simple table editing function implementation method
  • JavaScript to implement table sorting, editing, dragging and zooming
  • Baidu Editor takes values ​​from the Json object, completes the initial rendering, and draws a table in the editor
  • Editable.js is a jquery-based table editing plug-in

<<:  How to build php+nginx+swoole+mysql+redis environment with docker

>>:  MySQL startup error 1067 and invalid recovery after changing character set and restarting

Recommend

JS realizes the automatic playback effect of pictures

This article shares the specific code of JS to ac...

Summary of Kubernetes's application areas

Kubernetes is the leader in the container orchest...

Introduction to Vue3 Composition API

Table of contents Overview Example Why is it need...

Analyze the difference between computed and watch in Vue

Table of contents 1. Introduction to computed 1.1...

Vue+Openlayer realizes the dragging and rotation deformation effect of graphics

Table of contents Preface Related Materials Achie...

Tutorial on importing and exporting Docker containers

background The popularity of Docker is closely re...

Use personalized search engines to find the personalized information you need

Many people now live on the Internet, and searchin...

Detailed Introduction to MySQL Innodb Index Mechanism

1. What is an index? An index is a data structure...

HTML table layout example explanation

The elements in an HTML document are arranged one...

DHTML objects (common properties of various HTML objects)

!DOCTYPE Specifies the Document Type Definition (...

CSS overflow-wrap new property value anywhere usage

1. First, understand the overflow-wrap attribute ...

js to implement verification code interference (dynamic)

This article example shares the specific code of ...

CSS sample code with search navigation bar

This article shows you how to use CSS to create a...