Creating dynamic forms and tables on an HTML webpage

I'm struggling to dynamically add table elements and form elements in an HTML page. My goal is to automatically add input boxes with labels when a user enters a number in the input box without having to click any button. I believe using the 'keyup' event handler should help me achieve this, but I am having trouble implementing it in my code. Can someone please assist me by correcting my code or suggesting an alternative solution for my requirements?

HTML CODE:

<form>
    <input type="number" id="teamMemNum">
</form>
<table id="memNameTable"></table>

JAVASCRIPT:

<script type="text/javascript">
     $(document).ready(function(){
        $("#teamMemNum").on('keyup', function(){
            var num = $("#teamMemNum").val();
            var markup = "<tr><td><label for='memName'>Enter name: </label></td><td><input type='text' name='memName' id='memName'></td><td></td><td></td></tr>";
            for(var i = 0; i < num; i++){
                $("#memNameTable tbody").append(markup);
            }
        });
    });
</script>

Answer №1

Users have the ability to paste any number of rows.

It is important to refresh the table whenever the input field value is changed.

$(document).ready(function(){
        $("#teamMemNum").on('change paste keyup', function(){
            $("#memNameTable").html("");
            
            var num = $("#teamMemNum").val();
            var markup = "<tr><td><label for='memName'>Enter name: </label></td><td><input type='text' name='memName' id='memName'></td><td></td><td></td></tr>";
            for(var i = 0; i < num; i++){
                $("#memNameTable").append(markup);
            }
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="number" id="teamMemNum">
</form>
<table id="memNameTable"></table>

Answer №2

Your table appears to be empty, and you are attempting to insert new markup within the tbody. To resolve this issue, simply ensure that the tbody element is contained within your table.

<form>
    <input type="number" id="teamMemNum">
</form>
<table id="memNameTable">
  <tbody></tbody>
</table>

Answer №3

Seems like your setup is almost good to go, just need a minor tweak. In the loop, you're using the selector $("memNameTable tbody"), but in your HTML there's no tbody. You can either add tbody to the table in your HTML or adjust the selector to simply be $("memNameTable").

Answer №4

Key reminders:

  • To ensure accuracy, listen for the change event instead of the keyup event on your numeric input field (this accommodates cycling using the up and down arrows).

  • To determine how many rows to add, subtract the existing table row count from the value in the input field.

  • If there is no tbody, append directly to the table element.

$(document).ready(function() {
  $("#teamMemNum").on('change', function() {
    var num = $("#teamMemNum").val() - $('#memNameTable tr').length;
    var markup = "<tr><td><label for='memName'>Enter name: </label></td><td><input type='text' name='memName' id='memName'></td><td></td><td></td></tr>";
    for (var i = 0; i < num; i++) {
      $("#memNameTable").append(markup);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="number" id="teamMemNum">
</form>
<table id="memNameTable"></table>

Answer №5

It has been mentioned by others that you have forgotten to include the TBODY element in your TABLE.

Another valid point (which has already been raised) is that it would be better to use a broader event such as onBlur or onChange.

In my view, adding elements with identical IDs is not recommended as it can lead to non-compliant HTML - even though it may function correctly, it could cause issues for you or others in the future.

Personally, I prefer to avoid manipulating HTML strings and instead propose using a "dummy" line that will be disregarded when submitting the form:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="number" id="teamMemNum">
</form>
<table id="memNameTable">
  <tbody>
    <tr class="hidden sampleTR">
      <td><label for='memName' class="lineLabel">Enter name: </label></td>
      <td><input type='text' name='memName'></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>


<script type="text/javascript">
 $(document).ready(function(){
    $("#teamMemNum").on('change', function(e){
        var num = $("#teamMemNum").val();

        for(var i = 0; i < num; i++){

            //Clone a new line from the dummy sample (invisible) line
            var newLine = $('#memNameTable').find('tr.sampleTR').first().clone();

            //Generate a new id to be used
            var newID = 'memName_' + $('#memNameTable').find('tr').length;

            //Sets the new ID on the newLine elements
            $(newLine).find('input[name=memName]').attr('id', newID);
            $(newLine).find('label.lineLabel').attr('for', newID);

            //Append the newLine to the TBody of the Table
            $(newLine).appendTo($("#memNameTable tbody"));
        }
    });
});
</script>

Personally, this method makes it clearer to separate HTML from code.

Please note: the .hidden css class should be defined with a style like { display:none; } or an equivalent.

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 passport local strategy functions properly when tested with Postman, but encounters a "missing credentials" error when used with axios

I am currently working on creating a login system using passport and a local strategy. Strangely, when I attempt to send the request through axios it doesn't seem to work, although it functions properly with Postman. When using axios, I receive an er ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

Decoding JSON data in a Webmethod from an AJAX call

I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization: Error convert ...

Error in the Angular-UI calendar

I'm encountering an issue while trying to set up the angular-ui calendar. When I run it, I get the following error: TypeError: undefined is not a function at Object.eventsWatcher.onChanged (http://localhost/fisioGest/js/calendar.js:262:41) Despite b ...

Troubleshooting: Phonegap Not Responding to Ajax Requests

I've been trying to figure out how to make an ajax request work with PhoneGap, but I haven't had any luck so far. I'm using the latest version of PhoneGap and Android Studio. When I preview my app in AVD, everything looks good except for the ...

"Controlling Selected Options in Bootstrap Dual Listbox: A Guide to Limiting Choices

I am utilizing the Bootstrap Dual Listbox plugin to assist users in selecting specific options. I have successfully integrated this plugin into my project. However, I encountered an issue when attempting to impose a limit on the number of options a user ...

Scroll horizontally within the div before scrolling down the page

After reviewing other questions, it's important to note that the scroll I am looking for is horizontal, not vertical. My goal is to have a div on a page automatically start scrolling when it reaches the center or becomes visible, and then allow the pa ...

React: Component styles fail to update dynamically

I have been working on creating a component that can adjust its size dynamically based on props. Currently, I am experimenting with the code below, but I've noticed that when I change the slider, the component's size doesn't actually change. ...

Designing this unique shape using CSS3 to create a sleek drop-down container

My goal is to design something that resembles the following: The challenge lies in my preference to contain it within a single div, considering the drop-down features an inner shadow and a drop shadow. Thank you in advance, and please feel free to ask fo ...

Position the Figcaption over the Image

Running a website, I am facing an issue with adding copyright information to the top-left corner of an image. The img element is set to float:left; and the figcaption appears after it. However, there are some complications: 1) Using the position:absolute ...

Connect to a point on the leaflet map using an external <a> tag reference

I have a leaflet map and I am trying to create a link that, when clicked, will activate a specific marker on the map. Essentially, I want the linked marker to simulate being clicked when the link is clicked. Here is an example of the link: <a href="#" ...

Attempting to align two text boxes in the center using the text-align property

I've been attempting to center two text boxes using text-align. Unfortunately, they didn't align properly, as evident in this snapshot: https://gyazo.com/c47f4037ba1ab3abef5833358d94172e. What could have caused this misalignment, and how can it b ...

Having problems with the Save/Edit button functionality in JQuery?

I'm currently working on a day planner project for my class (check out the image below) and I'm facing some challenges in implementing an edit/save button feature. My goal is to have the button initially display "edit", and when clicked, allow us ...

Issues encountered when using v-model with JavaScript functions

Being a newcomer to Vue JS, I have been immersing myself in the official documentation to learn more about it. My current project is a straightforward task management web application. However, I seem to be encountering issues with the v-model directive a ...

Adapting data presentation based on user login status - using client-side logic

I've been contemplating the most effective approach to achieve this and considering potential bypasses. Here are my reflections. Currently, I have a series of links that reveal a detailed panel below upon clicking, showcasing additional information u ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

The prop HandleClick is not being identified

Whenever I click on the sidebar, my menu should appear, but instead I'm encountering an error message saying "react-dom.development.js:86 Warning: React does not recognize the handleClick prop on a DOM." import { useState } from "react"; imp ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

Passing Error from AngularJS Service to Controller

Service Function myService.serviceName = function (userId) { return $http({ method: 'POST', url: '/someUrl' }).then(function successCallback(response) { return ...

What is the best way to switch from http to https in a React application?

When performing audits in Chrome, I encountered a net::ERR_EMPTY_RESPONSE error because Lighthouse was not able to consistently load the requested page. Google developers have recommended configuring my server (possibly node.js) to redirect from http to ht ...