Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an issue with numbering the rows automatically starting from the second row. You can view my code progress so far on this jsfiddlelink.

$(document).ready(function(){

var gameRounds = [1, 2];

$(document).on("keyup", ".add", function() {
    var sum = 0;
    $(".add").each(function(){
        sum += +$(this).val();
    });
    $("#sum").text(sum);
});

var newRound = $('#newRound');

newRound.click(function(){
    $('.totals').before(
    "<tr>",
     "<td class='round'></td>",
     "<td class='p1'><input class='add' id='r1' type='number' name='r1'></td>",
    "</tr>"
    );

   console.log(gameRounds); 

});
});
table, th, td {
    border: 1px solid black;
}

table {
width: 15%;
}

.p1 {
background: lightblue;
}

.round {
width: 3em;
margin: auto;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="update">
  <thead>
    <th class="round">Round</th>
    <th class="p1">player1</th>
  </thead>
  <tr class="r1">
    <td class="round"></td>
    <td class="p1">
      <input class="add" id="r1" type="number" name="r1"></td>
  </tr>
  <tr>
    <td class="round"></td>
    <td class="p1">
      <input class="add" id="r2" type="number" name="r2">
    </td>
  </tr>
  <tfoot class="totals">
    <td class="round">total</td>
    <td class="p1">
      <span id="sum"></span>
    </td>
  </tfoot>

</table>

<div class="btnStyle">
  <button id="newRound">New Round</button> 
</div>

The button and calculator may not work on jsfiddle, but they function perfectly fine in Sublime Text and CodePen.

Answer №1

Check out this sample solution:

To implement it, create a new JavaScript function:

function numberRows() {
  var rowNum = 1;
  $('.row').each(function(index) {
    $(this).html(rowNum++);
  });
};

Call this function once the document is ready and whenever you add a new row.

View the comprehensive example here:

https://jsfiddle.net/Lqzyw4u4/8/

Answer №2

Great effort!

Prior to delving into the code, it's important to note that your JSFiddle wasn't functioning because you forgot to include the jQuery resource.

As for your code, instead of using an array to keep track of rows, consider simplifying by integrating row numbers directly into the existing HTML structure. This will streamline the process and eliminate the need for excessive data storage.

For example:

<tr class="r1">
    <td class="round">1</td>
    <td class="p1">
      <input class="add" id="r1" type="number" name="r1"></td>
  </tr>

To implement this, begin by adding row numbers to the current HTML content. Then, adjust your click function to increment the row count with each addition. Finally, update the table column with the new count.

newRound.click(function(){

    //Update number of rounds
    numGameRounds++;

    $('.totals').before(
        "<tr>",
        "<td class='round'>"+ numGameRounds +"</td>",
        "<td class='p1'><input class='add' id='r1' type='number' name='r1'></td>",
        "</tr>"
    );

    console.log(gameRounds); 

});

Check out the updated code here!

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

After performing a Vuex action on one Vue.js component, the update is not reflected on another Vue

I am facing an issue with a component that renders a booking table. When I update my store in another component, the table does not get updated even though the store and computed properties are updated. I suspect that the problem lies with the filter not b ...

JavaScript Polling Based on Time

I am currently working on developing an alarm clock feature using the Date() object. My aim is to have a function trigger when the time from the date object matches the time set by the user. Users set their alarms by selecting a specific time, but I' ...

The execution of the 'yarn start-https' command encountered an error and exited with code 1

Struggling to set up the environment for a downloaded project. After running yarn install, yarn build, and yarn start-https, I encountered this error message: Error: error:0909006C:PEM routines:get_name:no start line at node:internal/tls/secure-context ...

Transform a value nested at any depth into an object key using Ramda or plain JavaScript

I have encountered a unique scenario while using a specific library. Instead of returning an array, this library returns nested objects with the final leaf node containing the value. For instance: red.walk.fast.true is returned as {red: {walk: {fast: &apo ...

What is the process for using Discriminators, the Mongo DB API, and Mongoose to insert data into Cosmos DB?

Issue Overview I am currently facing a challenge in writing documents to my Cosmos DB using the Mongo DB API and Mongoose for Object Modeling. To optimize costs, I aim to store all documents in a single collection by utilizing Discriminators. The project ...

The rotation function of a THREE.js object seems to be malfunctioning

Currently, I am facing an issue with a Blender object that I have successfully displayed on my web page using THREE.js. However, for some reason the object is not rotating when my loop function is called. In my approach to working with JavaScript, I am tr ...

getting value of object property using a function that is located within the same object

I am attempting to access the 'context' property (or specifically 'context.settings') from within the 'ready' function in the same object. I am uncertain of the correct syntax to achieve this. Below is the code snippet: modu ...

Leveraging an array of Elasticsearch documents using AngularJS

The query results are given below... { "took": 6, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 45, "max_score": 0, "hits": [] }, "aggregations": { ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Cursor vanishes until mouse movement detected (Chrome browser)

In the HTML page I created, the mouse cursor is initially set to none. However, there are certain circumstances where I need it to switch to crosshair. The issue I am facing is that the cursor does not appear unless the user moves the mouse. If the mouse r ...

What is the NodeJs Event loop and how does it work with libuv and V8

NodeJs is made up of the V8 engine and the libuv library. The V8 engine has its own event loop with a call stack, event queue, and micro task queue to run our main code. The libuv also has an event loop with phases like times, callbacks, poll, check, and ...

What is the process for storing an array in AdonisJs migrations?

Having trouble saving an array into a PostgreSQL database! 'use strict' const Schema = use('Schema'); class UsersSchema extends Schema { up () { this.create('users', (table) => { table.increments(); t ...

Is there a way to ensure that the JSON data and the image appear on the same row with some spacing between them?

Trying to display JSON data with images and text side by side but facing issues where the text wraps below the image instead. How can I fix this layout to show text next to the image? Flex-wrap property doesn't seem to work as expected. function for ...

Looking to connect information

I have written the following code and I am trying to bind data to ng-model. When I use ng-model = "value", I can see the value in the text field, but I want to update the value when the text input is changed. <tbody ng-repeat="action in model.editAct ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Error in MVC Ajax with Int32 data type

Whenever I attempt to make an Ajax post request to my controller, I am faced with the following error message: The parameters dictionary includes a null entry for parameter 'id' of non-nullable type 'System.Int32' for method &a ...

Can you explain the significance of the jz element in HTML?

When visiting this particular page, it was noticed that the well-known ad blocking software successfully removed ads positioned near the top and right of the page. However, unexpectedly, this software added a brand new section of clickbait ads located just ...

What is the best way to manage various versions of JS libraries across different branches?

As a novice developer, I dabble in creating applications for personal use. My go-to tools are the Quasar framework for the front end and Python for the back end. I maintain a git repository where the master branch houses my "production code," but now I am ...

What is the process for creating a list using layers that are published in Geoserver?

I am currently working on developing a webmapping application. One of the tasks I need to accomplish is parsing the WMS request in order to retrieve the title of each layer within the layers section: var xhr = new XMLHttpRequest(); xhr.open(' ...

Accessing the URL '/Main/[object Object]' using the HTTP method POST is forbidden

Jquery method call: $.post({ url: "http://localhost:60700/Main//Data/dataServices.aspx", data: { action: "savePhoneData", phoneID: PhoneID, values : JSON.stringify(allData) }, success: phoneSaved, error: phoneSavedFaile ...