JQuery Delete row on dynamic tables

I am creating a registration page where a user can register several other people. I made it so that the table shows whether the user selects a specific option. I also added an add button and it adds lines perfectly. The problem is that when I add a function to the delete button, everything breaks. Here is my html:

<div id="add_table" style="display:none;" > <button type="button" id="AddLine">Add Line</button> <table border="1px" id="table"> <tr> <td>First Name</td> <td>Last Name</td> <td>Phone</td> <td>Email</td> <td>Ethnicity</td> </tr> <tr> <td><input type=text /></td> <td><input type=text /></td> <td><input type=text /></td> <td><input type=text /></td> <td><input type=text /></td> <td><button type="button">delete</button></td> </tr> </table>​ </div> 

And here is my jquery code:

 $(document).ready(function(e) { $("input[name= 'Reg_num_r']").change( function () { if($(this).val()==1) { $("#add_table").hide(); } else { $("#add_table").show(); } }); /*$("#table").on("click", "button", function() { $(this).closest("tr").remove(); });​*/ $("#AddLine").click(function () { var row = "<tr><td><input type=text /></td><td><input type=text /></td><td><input type=text /></td><td> <input type=text /></td><td><input type=text /></td><td><button type=button>delete</button></td></tr>"; $("#table").append(row); }); }); 

Now, when I uncomment the commented code above, everything stops working. The table simply does not appear, even if the user selects the correct option. How to fix it so that it performs the delete operation correctly?

+4
source share
1 answer

Ctrl + C Ctrl + V from your code:

 /*$("#table").on("click", "button", function() { $(this).closest("tr").remove(); });​*/ 

After the last half-column, a space of 0-width, click "Edit" and use the arrow keys to see it. This is an illegal character in JavaScript and generates a syntax error.

This is a common problem when copying code from jsFiddle and other places.

I would recommend having a copy of Notepad ++ on hand to view the copypasta code, it shows these invisible characters like ? default

enter image description here

You can also uncomment the code and test it in JSHint , it will tell you which line there is an invalid character.

+2
source

Source: https://habr.com/ru/post/1434505/


All Articles