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

Double the Trouble: jQuery AJAX Making Two Calls

I've already posted a question about this, but I have now identified the exact issue. Now, I am seeking a solution for it :) Below is my code snippet: $('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax&apos ...

Can curly braces be utilized in the style section of Vue.js?

Can I utilize curly braces in the style section of vue.js to set a value? For instance .container { background: url({{ image-url }}; color: {{ color-1 }} } ...

Puppeteer failing to detect dialog boxes

I'm attempting to simulate an alert box with Puppeteer for testing purposes: message = ''; await page.goto('http://localhost:8080/', { waitUntil: 'networkidle2' }); await page.$eval('#value&apos ...

Utilizing React forwardRef with a functional component

Looking at my code, I have defined an interface as follows: export interface INTERFACE1{ name?: string; label?: string; } Additionally, there is a function component implemented like this: export function FUNCTION1({ name, label }: INTERFACE1) { ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

Express displays HTML code as plain text

I am currently facing an issue where I am trying to display an html table on /guestbook.ejs and then redirect it to /guestbook. However, the content of my guestbook.ejs file is being displayed as plain text rather than rendering the HTML code. Below is th ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Encountering an issue with React npm causing errors that I am unable to resolve

Hey there, I'm a newbie to React. After setting everything up, I encountered an error after running "npm start." Can anyone help me figure out how to fix this? Thanks in advance! Click here for image description ...

If the color of the border matches and the width of the border is equal to

As I navigate through multiple divs, my goal is to identify those with a distinct blue border. Furthermore, if a main div possesses a blue border, I need to check for any inner divs that also have a blue border or a border width of 3px. If the main div has ...

Struggling with smoothly transitioning an image into view using CSS and JavaScript

I'm currently experimenting with creating a cool effect on my website where an image fades in and moves up as the user scrolls it into view. I've included the code I have so far below, but unfortunately, I keep getting a 404 error when trying to ...

The server mistakenly sent the resource as a Stylesheet even though it was interpreted differently

Dear Fellow Coders, Could anyone lend a hand? I encountered this issue on my website after uploading it to my FTP: "Resource interpreted as Stylesheet but transferred with MIME type text/plain" </head> <body> <div class= "navbar navbar ...

The art of fluidly positioning elements in Bootstrap columns

My goal is to showcase objects in 3 columns using Bootstrap 4. However, when I implement the code provided, the objects are only displayed in a single column, as shown here: example of 1 column layout. What I actually want is for the objects to be arrange ...

The JSX in React won't display the modified state on the user interface

In my diary object, I have records of 2 meals function Magicdiary() { const [diary, setDiary] = React.useState<MagicDiaryDay[]>([ { mealName: "Breakfast", ingredient: null }, { mealName: "Lunch", ingredient: null }, ]) ...

Display a pop-up directly below the specific row in the table

I am working on creating a table where clicking on a row will trigger a popup window to appear right below that specific row. Currently, the popup is displaying under the entire table instead of beneath the clicked row. How can I adjust my Angular and Bo ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Issue: Child Pages not found in Nuxt RoutingDescription: When navigating

Currently working on a Nuxt application that utilizes the WordPress REST API to fetch content. While my other routes are functioning correctly, I am facing challenges with nested pages. The structure I have implemented in my Nuxt app is as follows: pages ...

Tips for displaying dynamic images using the combination of the base URL and file name in an *ngFor loop

I have a base URL which is http://www.example.com, and the file names are coming from an API stored in the dataSource array as shown below: [ { "bid": "2", "bnam": "ChickenChilli", "adds": "nsnnsnw, nnsnsnsn", "pdap": " ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...