简体   繁体   中英

Why does JQuery show() function only work on one (rather than all) of elements with the selector?

JSFiddle .

In the following SSCCE, there is a <table> nested inside another <table> .

The question is about the click listener for #add button. Specifically, the last if/else block of the function. When you run this code, click the Add TextField button once (or more times), and you will see that the #remove button on which show() should be executed, is only shown for the first matched selector , and not both (or all) of them.

Ideally the Remove TextField should be shown for all the #remove selectors.

The question is why? How do I fix this?

 $(document).on("click", "button#add", function() { event.preventDefault(); var parentTable = $(this).parent().parent().parent().parent().parent().parent().parent().parent(); var lastTableRow = parentTable.children('tbody').children('tr:last'); //Adding the new row parentTable.children('tbody').append(lastTableRow.clone()); //Reset lastRow variable lastTableRow = parentTable.children('tbody').children('tr:last'); //Reset the fields lastTableRow.find('table tbody tr td input').each(function() { $(this).val(''); }); //update numberOfRows variable var numberOfRows = parentTable.children('tbody').children('tr').length; alert("numberOfRows:" + numberOfRows); //check if (!(numberOfRows > 1)) { $("#remove").hide(); } else { $("#remove").show(); } }); 
 #outer-table { padding: 20px; border: 3px solid pink; } #inner-table { border: 3px solid orange; } #remove { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="outer-table"> <tbody> <tr> <td> <table id="inner-table"> <tbody> <tr> <td> <p style="display:inline-block">Enter first complain:</p> <input type="text" /> </td> </tr> </tbody> <tfoot> <tr> <td> <button id="add">Add Textfield</button> <button id="remove">Remove Textfield</button> </td> </tr> </tfoot> </table> </td> </tr> </tbody> <tfoot> <tr> <td>Table Footer</td> </tr> </tfoot> </table> 

That's because you're using id for a group of objects. id should be unique per document. You should use a class name instead.

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