What is the reason why the show() function in JQuery only applies to one specific element, rather than all elements selected with the same selector?

JSFiddle.

This example code features a nested <table> within another <table>.

The main issue concerns the click listener for the #add button. Specifically, the final if/else statement in the function. When you execute this code and click the "Add TextField" button once or multiple times, you'll notice that the #remove button, where show() should be triggered, is only visible for the first matched selector, not all of them.

Essentially, the goal is to have the "Remove TextField" button displayed for all instances of the #remove selector.

The question at hand is: why does this occur? And how can it be resolved?

$(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());

  // Resetting the 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>

Answer №1

The reason for this issue is due to your utilization of the id attribute for a collection of elements. Each id should be distinct within a document. It's recommended to utilize a class name instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to adding customized CSS and JavaScript to a specific CMS page on Magento

I'm trying to incorporate a lightbox for video playback on a specific page of my CMS. I've placed my CSS file in JS/MY THEME/JQUERY/PLUGIN/VENOBOX/CSS/myfile.css and the JS files in JS/MY THEME/jquery/plugins/venobox/js/myfile.js, but it doesn&ap ...

Bootstrapvalidator does not function properly with select2.js

My code is not validating the select field. What could be causing this issue? Can anyone provide a solution? Apologies for my poor English, and thank you in advance for your response. Here is my form: <form name="form_tambah" class="form_tambah"> ...

Tips for updating one-time binding data in AngularJS

I am currently facing an issue with a div that displays details such as mobile number, name etc. in the format: {{::mobilenumber}}, {{::name}} Within this div, there is a button that when clicked should populate the same values in a new form However, des ...

Click once to change the element, but it will remain changed and will not revert back no matter how many times you

After the first click displaying "X" and then changing to "O" in my tic-tac-toe JavaScript game, subsequent clicks only show "O", failing to switch back to "X". I am currently working on creating a tic-tac-toe game using JavaScript. Upon the first click, ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

Using Selenium to interact with a checkbox in a React component's ::before pseudo-element

I've been attempting to select a checkbox, and here are some of the methods I have tested: //label[string()=('Notify user')]/i //div[@class='b-checkbox'] //div[@class='b-checkbox']//label//input[@type='checkbox&apo ...

Error: JSON parsing failed due to an unexpected token "u" at the beginning of the JSON string. This occurred in an anonymous function when

Implementing reCaptcha in my firebase project has been successful. I am now sending form data and the captcha response using grecaptcha.getResponse() to my server upon clicking the send button. Below is the code snippet from client.js: $('.sendUrl ...

Unable to locate the AngularJS controller after attempting to paste the code

Currently enrolled in the AngularJS Mastery Course on Udemy, I encountered an odd issue that has left me scratching my head. The code provided seems to function flawlessly for most users, except for a select few. index.html <html lang="en" ng-app=&apo ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

The ultimate guide to integrating bxslider with lightbox for stunning image galleries

My website features a small bxlider, and I would like to trigger a lightbox gallery to open when a slide is clicked. However, I am running into conflicts when using both scripts. Utilizing jQuery's noConflict() method is not resolving the issue. Does ...

Utilizing AJAX to retrieve data from a PHP function

Seeking to display the output of an AJAX call; This is my PHP code: if(isset($_POST['date']) ) { echo "<input type='radio' id='date'/>"; } And here's my AJAX code: $.ajax( { type: "POST", url: "sched ...

What are the initial and final functions in JQuery DataTableset.net?

My dataset is loaded in JQuery and displayed as a table using JQuery DataTable.net After destroying the table, I recreate it based on specific parameters: $('#mytables').DataTable().destroy(); $("table tbody").empty(); $.each(myobject, funct ...

How can the AngularJS model be updated while using long polling with Ajax?

How can I update the model using ajax long polling method? To start, I will load the default list: For example: - id1 - id2 - id3 Next, I set up an ajax long polling process in the background that runs every 5 seconds. When the ajax call receives an upd ...

Angular material chips showcase a row of five chips

I am working with the basic mat-chips from angular material and I want to arrange them in rows of five without increasing their size: Chip1 Chip2 Chip3 Chip4 Chip5 ..................(space left) Chip6 Chip7 Chip8 Chip9 Chip10 ...............(space le ...

The CSS background image is not functioning

.menubar li { float: left; width: 115px; text-align: center; background-image: url(js/left_main_bg_image.gif); } Having issues with the background image not displaying properly in IE, Firefox, and Chrome. I've tried adding it to a tab ...

What are the ways in which Angular can offer assistance to Internet Explorer 9?

The news is out - the Angular team has just announced their support for Internet Explorer 9! This revelation has left me wondering, how is it even possible? Currently, I am an avid user of AngularJS and have dedicated time to studying its ins and outs. Fr ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

One particular Django template is failing to load the CSS, while the rest of the templates are

In my folder, I have two Django templates. One template is for the URL localhost:8000/people and it correctly fetches CSS from /m/css/style.css. The problem arises with the second template meant for the URL localhost:8000/people/some-name. This template f ...

How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases. I attempted to calculate the total number of boxes that could fit based on their widths compared to the container ...

Create a div that vanishes when hovered over

I want to create a div element that disappears on hover using CSS without reappearing when moving the mouse again. While I know this can be achieved using JavaScript, I'm looking for a solution that incorporates CSS transitions for a smoother effect: ...