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

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

Issue with php and ajax causing loop malfunction

I'm currently working on building a simple USD to pounds converter using PHP and AJAX. While I know it would be simpler with jQuery, unfortunately, the use of jQuery is not allowed for this assignment. The problem I'm facing is that when I run th ...

Ways to prevent the corruption of a URL?

I have a method that calls a controller function from a script with arguments like this: $("#export-it-Voip").attr("href", '@Url.Action("ExportAllToExcel", "Home")?strvoicerecordfetchquery=' + voipquery + '&nSelectAllten=' + 10+&ap ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

Exploring the Combination of jQuery UI and ASP.NET

Right now, I am diving into the world of jQuery and struggling with a key concept. Working on web applications with ASP.NET means I need to stay in that realm, but integrating jQuery UIs is proving to be a challenge for me. My main question is: How can I ...

"Utilize the attr attribute to showcase an image within an HTML select element

I'm trying to showcase the flag of each country in a dropdown menu. Here is the code I attempted: <select id="slcCountry"> <option flag="https://restcountries.eu/data/afg.svg">AFG</option> <option flag="https://restcountr ...

Loading SVGs on the fly with Vue3 and Vite

Currently, I am in the process of transitioning my Vue2/Webpack application to Vue3/Vite. Here's an example of what works in Vue2/Webpack: <div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')" ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

Implement the parent jQuery library within a child iframe

I have a query regarding the use of two iframes in my HTML page. I am trying to implement a single jQuery file that is loaded on the parent page. The code snippet provided below works perfectly on all browsers, except for one issue with Chrome when using t ...

Creating JSON on iPhone using jQuery is a straightforward process that involves using the built-in

Is there a way to create a JSON object on an iPhone browser without using the "JSON" object? var json_string = JSON.stringify(array); I have been able to make a JSON object on a web browser using this code, but I'm not sure how to do it on an iPhone ...

What is the most effective method to override parent styles while utilizing CSS Modules?

I'm currently using NextJS along with CSS Modules for styling purposes. One of my goals is to adjust the appearance of a component in different scenarios: When it's rendered normally on a page, utilizing props to specify className modifiers. W ...

Trouble with AngularJS form validation not displaying

I am struggling to display error messages using the AngularJS form validation code below. It involves a nested loop where I attempt to validate a dropdown box with questions and their corresponding answers. Here is a snippet of the code: HTML <form na ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

Is there a way I can position my privacy alert so that it appears in front of all DIVs, RevSlider,

Have you had a chance to visit my website at ? I recently added a privacy alert in compliance with the new EU Regulation. However, I'm facing an issue where the alert is overlapping with some of my website components such as other DIVs and Revolution ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

What tool can be used for formatting and syntax highlighting when working with ejs (embedded javascript) templates?

When working on my project, I utilize EJS as the express templating engine. While it is user-friendly and efficient, I have encountered difficulties when it comes to editing files - the text highlighting could be better, and I have not been able to find an ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

Packages starting with @ are found in the Node.js ecosystem

What's the deal with libraries in Node.js starting with @ symbols? Is there a specific convention for this? I feel like I'm missing something obvious here. ...

Update the iframe located on a different webpage

I am looking to create a dynamic button feature on my website where clicking a button on page1.html will open a new page (portal.html) with an iframe displaying the URL specified in the button. The setup involves two main pages: page1.html, and portal.htm ...

The Ajax function is not defined and results in a runtime error being thrown

customAjax.postJson( "/foo/GetFoo", { fooName: fooName }, function (data) { }, function (error) { }); }; My Rest api call is GetAsync() It throws customAjax is unde ...