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

What is the best way to implement a switch that can simultaneously display both the on and off positions?

I need help customizing a toggle switch element in CSS. I want the first row to display as on (blue color) and the second and third rows to be displayed as off or grey. So far, my attempts to modify the CSS code have been unsuccessful. .switch { posi ...

Content Remains Visible in Inspector Despite Display Being Set to None

I've got a WordPress site set up currently where I want to hide the header and footer while still loading them. I attempted using CSS to hide them by setting their display to none, but they continue to show up on the website. Is there a proper way to ...

stop initial focus on input field in Ionic

One issue I'm facing is that my login screen for the application automatically focuses on the 'username' input field and triggers the keyboard to pop up. This causes the contents of the login screen to push up, resulting in incorrect dimensi ...

Placing a div with absolute positioning inside another div with absolute positioning raises the question of how it functions when the outer div is not set to position: relative

Trying to grasp the concept, I experimented with the following setup: <div id="Outer"> <div id="Inner"></div> </div> In this scenario, the outer div has a relative position and the inner div has an absolute position. This allo ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Establish an angular scope within the DOM element

I am facing a challenge in creating a new Angular scope and attaching it to a DOM element. The situation is complicated by the fact that I am working on modifying a third-party control and cannot simply use a directive. My approach so far has been: ... = ...

Tips for including a permanent button at the bottom of a material ui dialog box

I want to implement a dialog popup in my react js application. When the user clicks on a button, the dialog should open up. Inside the dialog, there is a form with input fields. After the user fills out all the inputs, they can submit the information by cl ...

When the window is resized, the div shifts position

I recently added a div to my website with the following code: <div id="div"></div> #div { height: 400px; width: 300px; position: absolute; right: 59%; text-align: left; } Howe ...

What is the best way to ensure the right six-column DIV remains at the top in responsive web design?

I have implemented a custom 12-column grid and have created a row structure as follows: <div class="row"> <div id="the-pink" class="lg-6 md-12 sm-12"><!-- content --></div> <div id="the-violet" class="lg-6 md-12 sm-12"&g ...

I seem to be stuck trying to figure out what's going wrong when receiving JSON data

I have spent hours researching on Stack Exchange and Google to gather different information. Here is what I have in guess.php: PHP header('Content-type: application/json'); get_rating($cleanMovie); json_encode(array($id)); The get_rating funct ...

Tips for validating a text box within a dynamically created HTML table (grid)

I am seeking assistance with validating the values in each text box within a dynamically generated HTML table (grid). Upon clicking the save button, I want to check all textbox controls and validate whether they contain a value or not. Any help on this mat ...

Utilizing CSS in Angular applications

I am currently working on an Angular 2 application and I am fairly new to Angular. I am facing an issue where my CSS does not seem to be applying properly. There are three key files involved: landing.component.html landing.component.scss landing.compone ...

Set the style to be displayed as a block element

I am working on a Rails application that contains some <li> elements with the CSS property display: none;. I want these elements to only appear on the page when they are being dragged. However, there are some elements that do not have the display: no ...

File input does not prompt the file browser on Android devices, limiting users to only the camera option

I created a basic web application where users can upload images. The frontend is built using HTML5 and some jQuery within a simple Ruby on Rails app. Everything functions smoothly, except for Android devices where only the Camera option is available when ...

Increase division height when mouse hovers over it

I want the height of the div to be 50px by default and change to 300px onmouseover. I have implemented this as follows: <style type="text/css"> #div1{ height:50px; overflow:hidden; } #div1:hover{ height:300px; } </style> <body> <div i ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

Launching ng-app for AngularJS after the page has finished loading

After loading content with jQuery AJAX that includes ng-app="" and other directives, the AngularJS initialization does not occur. How can I initialize an ng-app that was added after the page has already been loaded? <script src="https://ajax.googleap ...

Tips for Incorporating Multiple Stops into Your Google Maps Route

I am currently integrating the gmaps API with JQuery to showcase directions from point A to point B and then to point C on a map. Despite implementing the code below, I am encountering some issues: <script type="text/javascript"> var map; ...

Displaying Dates in an Express Application using EJS

I have a MySQL table with a column containing date data. I am building a webpage to display this data in a more user-friendly way. Currently, the displayed result looks like this: I would like the dates in the column to be formatted as something like ...

Using jQuery to dynamically insert an HTML element into a table

I'm trying to insert a hyperlink into an empty HTML table. This function works perfectly fine on Firefox and Chrome, taking only 0.2 seconds to load. However, when I try it on IE9, it takes at least 3 minutes to display the link. The issue seems to be ...