


How to dynamically add and delete table rows with native JS and JQuery_javascript skills
The example in this article describes how to dynamically add and delete table rows using native JS and JQuery. Share it with everyone for your reference. The specific analysis is as follows:
The following HTML code functions: Submit a form and submit the value of the check box (the value of the check box is equal to the following text box, the check box and text box are on the same line, and can be added and deleted dynamically).
Original JS version:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>javascript添加行demo</title> <script type="text/javascript"> /**验证表单复选框是否有选择*/ function isValidChkSelect(frm){ var chk = frm.chked; if(chk == undefined){ return; } var len = frm.chked.length; if(chk.length == undefined){ // 只有一个checkbox if (chk.checked == true) { return true; } } else { for(var i = 0; i < chk.length; i++) { if (chk[i].checked == true) { return true; } } } return false; } /**选择所有文本框*/ function selectAll(frm){ for (var i = 0; i < frm.elements.length; i++){ var e = frm.elements[i]; if (e.name != 'chkall' && e.type == 'checkbox') e.checked = frm.chkall.checked; } } /**添加新行*/ function addNew(){ var objMyTable = document.getElementById("tbl"); var index = objMyTable.rows.length - 1; var nextRow = objMyTable.insertRow(index);// 插入新行 var objCel_0 = nextRow.insertCell(0);// 添加单元格 objCel_0.innerHTML = "<input type='checkbox' name='chked' value='' />"; var objCel_1 = nextRow.insertCell(1); // nextRow.rowIndex -- 行索引 objCel_1.innerHTML = "<input type='text' name='newRow"+nextRow.rowIndex+"' /> <a href='#' onclick='delRow(this)'>删除</a>"; } /**删除行对象*/ function delRow(obj){ //obj.parentNode.parentNode.removeNode(true); // Firefox不兼容 var new_tr = obj.parentNode.parentNode; var tmp = new_tr.parentNode; tmp.removeChild(new_tr); // 删除子节点 } /**将文本框值赋给同一行对应的复选框*/ function setValue(obj, obj_chk){ obj_chk.value = obj.value; } function doSubmit(frm){ if(isValidChkSelect(frm) == false){ alert("选择不能少于一项"); return false; } for(var i = 0; i < document.getElementsByTagName("input").length; i++) { var obj = document.getElementsByTagName("input")[i]; if(obj.type == "text" && obj.name.substring(0, 6) == "newRow"){ var obj_chk = obj.parentNode.parentNode.childNodes[0].childNodes[0];// 复选框对象 if(valid(obj, obj_chk)){ setValue(obj, obj_chk);// 同一行的文本框值 赋值给 复选框 continue; } else { return false; } } } return true; } function valid(obj, obj_chk){ if(obj_chk.checked){ var patrn = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; if(obj.value == ""){ alert("添加的地址不能为空!"); return false; } if(!patrn.test(obj.value)){ alert("请输入正确的邮件地址!"); return false; } } return true; } </script> </head> <body> <form method="post" action="" onsubmit="return doSubmit(this)"> <table id="tbl" border="1" cellpadding="4" style="border-collapse: collapse" width="100%"> <tr> <td><input type="checkbox" name='chkall' onclick="selectAll(this.form)"/>全部选择</td> <td> 允许发送地址 <a href="#" onclick="addNew()">添加新地址</a> </td> </tr> <tr> <td> <input type="checkbox" name="chked" value="mailfrom@gmail.com"> </td> <td>mailfrom@gmail.com</td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交" name="B1"> </td> </tr> </table> </form> </body> </html>
JQuery version:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jQuery添加行demo</title> <script type="text/javascript" src="jquery-1.6.4.min.js"></script> <script type="text/javascript"> $("document").ready(function(){ // 全部选择的点击事件 $("input[name='chkall']").click(function(){ $("input[name='chked']").attr("checked", this.checked); }); }); var row_cur_index = 0;// 插入行的当前索引 /**添加新行*/ function addNew(){ var row_id = "tr" + row_cur_index;// 所插入行的id var row_obj = "<tr id='"+row_id+"'><td><input type='checkbox' class='ck_class' name='chked' value='' /></td><td><input type='text' name='newRow"+row_cur_index+"' /> <a href='#' onclick='delRow("+row_id+")'>删除</a></td></tr>"; $("#topRow").before(row_obj); // 插入行 row_cur_index = row_cur_index + 1; } /**将文本框值赋给同一行对应的复选框*/ function setValue(row_index, value){ var row_id = "#tr" + row_index; $(row_id).find(":checked").val(value); } /**删除行对象*/ function delRow(row_id){ $(row_id).remove(); // 删除匹配row_id的元素 } function doSubmit(frm){ /**判断复选框是否有选*/ if($("input[name='chked']:checked").size() == 0){ alert("选择不能少于一项"); return false; } try { $("tr[id^='tr']").each(function(){ var tmp_row_index = this.id.substring(2); // 当前行索引 if($("#tr"+tmp_row_index).find(":checkbox").attr("checked")){ var patrn = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; var input_value = $("input[name='newRow"+tmp_row_index+"']").val(); // 文本框值 setValue(tmp_row_index, this.value); if(input_value == "") throw "Err1"; if (!patrn.test(input_value)) throw "Err2"; } }); } catch (e) { if(e == "Err1") alert("添加的地址不能为空!"); if(e == "Err2") alert("请输入正确的邮件地址!"); return false; } return true; } </script> </head> <body> <form method="post" action="" onsubmit="return doSubmit(this)"> <table id="tbl" border="1" cellpadding="4" style="border-collapse: collapse" width="100%"> <tr> <td><input type="checkbox" name='chkall' />全部选择</td> <td> 允许发送地址 <a href="#" onclick="addNew()">添加新地址</a> </td> </tr> <tr> <td> <input type="checkbox" name="chked" value="mailfrom@gmail.com"> </td> <td>mailfrom@gmail.com</td> </tr> <tr id="topRow"> <td colspan="2"> <input type="submit" value="提交" name="B1"> </td> </tr> </table> </form> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.