Enhancing dynamic text boxes with jQuery by incorporating additional information

I've recently developed an interactive app that dynamically creates tables based on user input. The app includes a feature where you can specify the number of tables to generate and track the total count of tables added.

Currently, I'm exploring ways to enhance the app by allowing users to input their name or any custom text which will then be displayed in a designated 'Name' box upon clicking the 'Add now' button. Despite numerous attempts, I haven't been successful in modifying the existing functionality to accommodate this text display feature.

You can explore the live version of this project here: http://codepen.io/BabinecJ/pen/BRjJbw

$('[name="cand_no" ]').on('change', function() {
  // Implementing logic for valid inputs
  if (this.value != '') {
    var val = parseInt(this.value, 10);
    
    $(function() {
      $('#add').bind('click', function() {
        var count = $('#mytbody').children('tr').length;
        $('#counter').html(count);
        
        var name = $("#tname").val();
        $('#name').html(name);
      });
    });

    $(document).ready(function() {
      $('cand_no').keydown(function(event) {
        if (event.keyCode == 13) {
          event.preventDefault();
          return false;
        }
      });
    });

    for (var i = 0; i < val; i++) {
      var $cloned = $('.template tbody').clone();
      $('#studentTable tbody').append($cloned.html());
    }
  }
});
.template {
  border-style: solid;
}

#cand_no {
  background-color: red;
}

#add {
  color: red;
  margin-right: 770px;
  margin-top: -35px;
}

Answer №1

Based on the MDN documentation for id: "The id global attribute specifies a unique identifier (ID) that must be distinct throughout the entire document."1

To adhere to this rule, adjust the id attribute of the target element (in this case, <p id="tname">) to ensure its uniqueness. The current code snippet looks like this:

<td> <p>Number of rows: <p id="counter"></span></p></td>

<td>Name<p id="tname"></span></p></td>

An updated version might look something like this:

<td> <p>Number of rows: <p id="counter"></span></p></td>

<td>Name<p id="aname"></span></p></td>

Remember to also modify the JavaScript code that interacts with this element, as illustrated below:

 $('#aname').html(name);

Check out a showcase of this implementation below:

$('[name="cand_no" ]').on('change', function() {
  // Omitting input validation
  if (this.value != '') {
    var val = parseInt(this.value, 10);
    ///Click add button add count number + table

    $(function() {
      $('#add').bind('click', function() {
        $('#mytbody');
        var count = $('#mytbody').children('tr').length;
        $('#counter').html(count);
        ///need to find enter coder name 
        var name = $("#tname").val();
        $('#aname').html(name);
      });
    });
    /// Figuring out way to disable enter key being pressed
    $(document).ready(function() {
      $('cand_no').keydown(function(event) {
        if (event.keyCode == 13) {
          event.preventDefault();
          return false;
        }
      });
    });
    for (var i = 0; i < val; i++) {
      // Clone the Template
      var $cloned = $('.template tbody').clone();
      // For each number added append the template row
      $('#studentTable tbody').append($cloned.html());
    }
  }
});
.template {
  border-style: solid;
}

#cand_no {
  background-color: red;
}

#add {
  color: red;
  margin-right: 770px;
  margin-top: -35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <label><strong>Number of Rows</strong></label>
  <label><input name="cand_no"  type="text" placeholder="Type Number of Rows" id="cand_no" /></label>

<div style="float: right; width: 40px">
    <button id="add">Add row</button>
</div>
  <div class="clear"></div>
</p>
<p>
  <label><strong>Your Name</strong></label>
  <label><input name="tname" id="tname" type="text" placeholder="Type Your Name"  /></label>
  <div class="clear"></div>
</p>


<div class="cand_fields">
  <table id="studentTable" width="630" border="solid">
    <tbody id="mytbody">
      <tr>
        <td>
          <p>Number of rows:
            <p id="counter">
              </span>
            </p>
        </td>

        <td id="tname" width="0">Nameee
          <p id="aname">
            </span>
          </p>
        </td>
      </tr>
      <tr>
        <td><input name="tname" type="text" placeholder="name" required="required" id="tname" /></td>

        <td><input name="cand_pos" type="text" placeholder="Name" required="required" /></td>
      </tr>
  </table>
</div>

<div class="template" id=".template" style="display:none ">
  <table>


    <tr>
      <td><input name="cand_name" type="text" placeholder="Count" required="required" id="count" /></td>

      <td><input name="cand_pos" type="text" placeholder="Name" required="required" /></td>
    </tr>
    </tbody>
  </table>
</div>


1https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

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

The execution of jQuery Ajax requests with "when" is encountering issues

My goal is to initiate 8 ajax GET requests N number of times, and this is the code I have written: var me = this; urls.forEach(function(requests){ $.when(requests.map(function(request){ return $.ajax(request) })).done(function(data){ me.result ...

A minimalist web page appearing as blank in Internet Explorer

After testing my simple web page in various browsers, I discovered that it only showed a blank white page in Internet Explorer. I combed through my CSS code and identified background = rgba(some stuff) as the unsupported line by IE. However, this particula ...

Angular 5 and Bootstrap card with enhanced double-click functionality

I want to design a Bootstrap card that can trigger two of my custom methods. <div (click)="TEST1()" class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <button (click)="(T ...

Selecting a language by clicking on it

I recently designed a bootstrap navigation bar for my website and incorporated a language selection dropdown menu into it. <li class="nav-item dropdown"> <a class="nav-link dropright" href="#" id="navbarDropdown" role="button" data-toggle="dr ...

Hover over the text below to see an image appear in its place

I'm looking to swap out some text with an image when hovering over it, using basic HTML/CSS. NO: show the image below the text NO: display the text on top of the image NO: replace one image with another YES: replace the text with an image ...

Is there a way to adjust the placement of this AccordionDetails utilizing Material UI's Grid system?

Here is a sketch of what I am aiming for: This is my implementation using Material UI's Accordion component. Below is the code snippet for the AccordionDetails section, which is where I need assistance. Specifically, I want to align FilterC/the swit ...

Using the CSS property `transform:scale(2,2)` causes an image to suddenly appear in the

Currently utilizing Joomla 3.3, I am seeking to enlarge an image on mouseover. The html code for the image is as follows: <img class="enlarge" style="float: right; margin: 10px; border: 5px solid black;" title="Chapter 1: Physical Differences" src="im ...

Is there a way to automatically select all checkboxes when I select contacts in my case using Ionic 2?

initializeSelection() { for (var i = 0; i < this.groupedContacts.length; i++) { for(var j = 0; j < this.groupedContacts[i].length; j++) this.groupedContacts[i][j].selected = this.selectedAll; } } evaluateSelectionStatus() { ...

Is it possible to refresh text in table without clearing icons?

Is there a way to maintain icons in table rows when editing text fields from a dialog? Currently, regardless of whether I use .html() or .text(), the icons disappear. I suspect that utilizing .content() may be a solution, but I'm unsure how to impleme ...

Tips for dynamically resetting the dataTable

When I create a datatable and add rows dynamically based on the selected option, I encounter an issue where I need to reinitialize the dataTable every time the option is changed. To address this, I have placed the reinitialization code inside the $("#selec ...

Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to dis ...

``Passing a database value from a controller to a table popup through AJAX: A step-by

I need to display a popup containing data from a database. I'm using an AJAX function with onclick() to achieve this. The data retrieved will be shown in the popup, which includes a table. However, I'm unsure how to properly display the data with ...

What is the best approach to creating a website for a client who needs to incorporate their own Youtube videos?

Welcome to my first post on this platform! I have a new project where I am creating a website for a client who wants to easily embed their own YouTube links. As a beginner in web development, this is my first paid task and I'm curious about how I can ...

Experiencing Difficulty Retaining Checkbox State Using LocalStorage Upon Page Reload

At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox. However, I'm facing an issue ...

Turning my dual button navigation into tabs to display distinct HTML pages beneath a designated header

body{ background:url(background.jpg); background-size: cover; } h1{ font-family: 'Dancing Script', cursive; font-size: 5em; color: white; text-align: center; margin-top: 25px; margin-bottom: 20px; } h2{ font-size: 18px; color: white; text-align ...

Having difficulty adjusting the padding of the Material UI table

I have been using the Table component provided by the material-ui library in my React project. However, I have encountered an issue where each row, including the header, has a padding of 24px on the top and bottom that I am unable to modify or overwrite. D ...

I have developed a website that can calculate the factorial of any given number. The next step is to design a function that will display the step-by-step mathematical process

Could use a hand with this one. The function below is empty and I'm a bit stuck on what to do next. Right now, the webpage displays the factorized number, but I want to show the mathematical equation before it, like so: User inputs: 3 Site outputs: " ...

"Exploring the Possibilities: Foundation 4 Reveal and WP AJAX for Creating Previous/Next Modal Windows within an Open Modal

I am currently in the process of developing a personalized gallery that integrates WordPress and Zurb Foundation: The layout showcases an organized collection of custom posts on different pages; these are displayed as a grid of linked thumbnails through ...

Warning: multiple selections have been made on the checkboxes

Currently, I am using FormData to submit data and trying to alert the values of checked checkboxes in my form. At the moment, I can only make it work for one checkbox. How can I alert the values of all checked checkboxes? var formData = new FormData(docu ...

Harness the power of Jquery with the masonry('hide', element) method on a carefully selected jquery element

Currently, I am utilizing Masonry to create a dynamic layout on my website but have encountered an issue with its hide and reveal functions. During an event, the following code is being executed: $container.masonry('hide', $(this)); It seems ...