Requirement description:
The user clicks the button on the page to display the data in the text box in a new line of the table, as shown in the following figure:
If one item in the input box is empty, the pop-up dialog box'Please fill in the data completely.
Steps:
1. Button Register Click Events
2. Get and judge the contents of text boxes
4. Create rows and add them to tbody
5. Create columns and set content
6. Add columns to rows
Code:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Add tables to the page</title> 6 <style> 7 * { 8 margin: 0; 9 padding: 0; 10 } 11 12 div { 13 width: 400px; 14 margin: 100px auto; 15 } 16 table { 17 margin-top: 10px; 18 width: 400px; 19 border: 2px solid #000; 20 border-collapse: collapse; 21 } 22 table thead tr { 23 background-color: purple; 24 color: #e0e0e0; 25 } 26 27 table tr { 28 background-color: pink; 29 } 30 31 table td { 32 text-align: center; 33 border:1px solid #000 ; 34 } 35 36 table td:nth-child(1){ 37 width: 100px; 38 } 39 40 table td:nth-child(2){ 41 width: 300px; 42 } 43 </style> 44 </head> 45 <body> 46 <div> 47 <label for="">Please input your name:</label> 48 <input type="text" class="uname"><br /> 49 <label for="">Please input the mailbox:</label> 50 <input type="email" class="email"><br /> 51 <button>Add to</button><br /> 52 <table> 53 <thead> 54 <tr> 55 <td>Full name</td> 56 <td>mailbox</td> 57 </tr> 58 </thead> 59 <tbody> 60 <!-- Dynamic addition of content --> 61 </tbody> 62 </table> 63 </div> 64 65 <script> 66 // Get elements 67 var uname = document.querySelector('.uname'); 68 var email = document.querySelector('.email'); 69 var btn = document.querySelector('button'); 70 var tbody = document.querySelector('tbody'); 71 72 btn.onclick =function () { 73 //Check that the input is not empty 74 if(uname.value === '' || email.value === '') 75 alert('Please enter the content'); 76 else { 77 //Create node 78 var tr = document.createElement('tr'); 79 var td1 = document.createElement('td'); 80 var td2 = document.createElement('td'); 81 //Getting element content 82 td1.innerHTML = uname.value; 83 td2.innerHTML = email.value; 84 //Add content to the table 85 tr.append(td1); 86 tr.append(td2); 87 tbody.append(tr); 88 } 89 } 90 </script> 91 92 </body> 93 </html>
Effect:
Now enter: name: Xiaoming - > click the Add button to add