Dynamic form in Asp.net framework and Jquery not handling the index recalculation

I’m working on a form that allows users to dynamically add and remove expense rows using jQuery. The issue I’m facing is with maintaining sequential indexes for each row, even after adding or removing rows.

Here’s the scenario:

The form allows users to add multiple expense rows, where each row has fields for description, expense date, and amount.
The index for each row should be sequential (e.g., 0, 1, 2, …) and should update correctly when rows are removed.

This is the html form

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@model ExpenseApplication.Models.ViewModels.ExpenseFormViewModel
@using (Html.BeginForm("AddExpense", "Employee", FormMethod.Post))
{
<div id="expenseData" data-expense-index="@Model.Expenses.Count"></div>
<h2>Create Expense Form</h2>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Currency, "Currency")
@Html.DropDownListFor(m => m.Currency, Model.CurrencyList, "Select a currency--", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Currency, "", new { @class = "text-danger" })
</div>
<h3 class="mt-3">Expenses</h3>
<table class="table">
<thead>
<tr>
<th>Description</th>
<th>Expense Date</th>
<th>Amount</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="expensesTable">
@for (int i = 0; i < Model.Expenses.Count; i++)
{
<tr>
<td>
@Html.TextBoxFor(m => m.Expenses[i].Description, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Expenses[i].Description, "", new { @class = "text-danger" })
</td>
<td>
@Html.TextBoxFor(m => m.Expenses[i].ExpenseDate, new { @class = "form-control", type = "date" })
@Html.ValidationMessageFor(m => m.Expenses[i].ExpenseDate, "", new { @class = "text-danger" })
</td>
<td>
@Html.TextBoxFor(m => m.Expenses[i].Amount, new { @class = "form-control amountInput" })
@Html.ValidationMessageFor(m => m.Expenses[i].Amount, "", new { @class = "text-danger" })
</td>
<td>
<button type="button" class="btn btn-danger removeExpense">Remove</button>
</td>
</tr>
}
</tbody>
</table>
<button type="button" id="addExpense" class="btn btn-primary">Add Expense</button>
<div>
<strong>Total Amount:</strong> <span id="totalAmount">0.00</span>
</div>
<div>
<button type="submit" class="btn btn-success" id="expenseForm">Submit Expense Form</button>
</div>
}
</code>
<code>@model ExpenseApplication.Models.ViewModels.ExpenseFormViewModel @using (Html.BeginForm("AddExpense", "Employee", FormMethod.Post)) { <div id="expenseData" data-expense-index="@Model.Expenses.Count"></div> <h2>Create Expense Form</h2> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(m => m.Currency, "Currency") @Html.DropDownListFor(m => m.Currency, Model.CurrencyList, "Select a currency--", new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Currency, "", new { @class = "text-danger" }) </div> <h3 class="mt-3">Expenses</h3> <table class="table"> <thead> <tr> <th>Description</th> <th>Expense Date</th> <th>Amount</th> <th>Actions</th> </tr> </thead> <tbody id="expensesTable"> @for (int i = 0; i < Model.Expenses.Count; i++) { <tr> <td> @Html.TextBoxFor(m => m.Expenses[i].Description, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Expenses[i].Description, "", new { @class = "text-danger" }) </td> <td> @Html.TextBoxFor(m => m.Expenses[i].ExpenseDate, new { @class = "form-control", type = "date" }) @Html.ValidationMessageFor(m => m.Expenses[i].ExpenseDate, "", new { @class = "text-danger" }) </td> <td> @Html.TextBoxFor(m => m.Expenses[i].Amount, new { @class = "form-control amountInput" }) @Html.ValidationMessageFor(m => m.Expenses[i].Amount, "", new { @class = "text-danger" }) </td> <td> <button type="button" class="btn btn-danger removeExpense">Remove</button> </td> </tr> } </tbody> </table> <button type="button" id="addExpense" class="btn btn-primary">Add Expense</button> <div> <strong>Total Amount:</strong> <span id="totalAmount">0.00</span> </div> <div> <button type="submit" class="btn btn-success" id="expenseForm">Submit Expense Form</button> </div> } </code>
@model ExpenseApplication.Models.ViewModels.ExpenseFormViewModel

@using (Html.BeginForm("AddExpense", "Employee", FormMethod.Post))
{
    <div id="expenseData" data-expense-index="@Model.Expenses.Count"></div>
    <h2>Create Expense Form</h2>

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(m => m.Currency, "Currency")
        @Html.DropDownListFor(m => m.Currency, Model.CurrencyList, "Select a currency--", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Currency, "", new { @class = "text-danger" })
    </div>

    <h3 class="mt-3">Expenses</h3>
    <table class="table">
        <thead>
            <tr>
                <th>Description</th>
                <th>Expense Date</th>
                <th>Amount</th>
                <th>Actions</th> 
            </tr>
        </thead>
        <tbody id="expensesTable">
            @for (int i = 0; i < Model.Expenses.Count; i++)
            {
                <tr>
                    <td>
                        @Html.TextBoxFor(m => m.Expenses[i].Description, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Expenses[i].Description, "", new { @class = "text-danger" })
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.Expenses[i].ExpenseDate, new { @class = "form-control", type = "date" })
                        @Html.ValidationMessageFor(m => m.Expenses[i].ExpenseDate, "", new { @class = "text-danger" })
                    </td>
                    <td>
                        @Html.TextBoxFor(m => m.Expenses[i].Amount, new { @class = "form-control amountInput" })
                        @Html.ValidationMessageFor(m => m.Expenses[i].Amount, "", new { @class = "text-danger" })
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger removeExpense">Remove</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>

    <button type="button" id="addExpense" class="btn btn-primary">Add Expense</button>

    <div>
        <strong>Total Amount:</strong> <span id="totalAmount">0.00</span>
    </div>

    <div>
        <button type="submit" class="btn btn-success" id="expenseForm">Submit Expense Form</button>
    </div>
}

And here is the javascript code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var expenseIndex = $('#expensesTable tr').length; // Initialize expenseIndex to the number of existing rows
// Add new expense row
$('#addExpense').click(function () {
var newRow = `<tr>
<td><input type="text" name="Expenses[${expenseIndex}].Description" class="form-control" /></td>
<td><input type="date" name="Expenses[${expenseIndex}].ExpenseDate" class="form-control" /></td>
<td><input type="number" name="Expenses[${expenseIndex}].Amount" class="form-control amountInput" /></td>
<td><button type="button" class="btn btn-danger removeExpense">Remove</button></td>
</tr>`;
$('#expensesTable').append(newRow);
// After adding a new row, reindex all rows
expenseIndex++
calculateTotal();
});
$(document).on('click', '.removeExpense', function () {
$(this).closest('tr').remove();
reindexExpenses();
calculateTotal();
});
function reindexExpenses() {
// Reindex each row to ensure sequential indexes
$('#expensesTable tr').each(function (index) {
$(this).find('input').each(function () {
let field = $(this).attr('name');
if (field) {
// Update the name attribute to reflect the current index
var newName = field.replace(/Expenses[d+]/, `Expenses[${index}]`);
$(this).attr('name', newName);
}
});
});
// Update the expenseIndex to reflect the current number of rows
expenseIndex = $('#expensesTable tr').length;
}
// Calculate total expense amount
function calculateTotal() {
var total = 0;
$('.amountInput').each(function () {
var amount = parseFloat($(this).val()) || 0;
total += amount;
});
$('#totalAmount').text(total.toFixed(2)); // Update total amount display
}
// Update total amount on input change
$(document).on('input', '.amountInput', function () {
calculateTotal();
});
// Recalculate total on page load
$(document).ready(function () {
calculateTotal();
});
// Validate form before submission to ensure at least one expense
$('#expenseForm').click(function (e) {
var expensesCount = $('#expensesTable tr').length;
if (expensesCount === 0) {
Swal.fire({
icon: 'warning',
title: 'No Expenses Added',
text: 'At least one expense must be added.',
confirmButtonText: 'OK'
});
e.preventDefault(); // Prevent form submission if no expenses
}
});
</code>
<code>var expenseIndex = $('#expensesTable tr').length; // Initialize expenseIndex to the number of existing rows // Add new expense row $('#addExpense').click(function () { var newRow = `<tr> <td><input type="text" name="Expenses[${expenseIndex}].Description" class="form-control" /></td> <td><input type="date" name="Expenses[${expenseIndex}].ExpenseDate" class="form-control" /></td> <td><input type="number" name="Expenses[${expenseIndex}].Amount" class="form-control amountInput" /></td> <td><button type="button" class="btn btn-danger removeExpense">Remove</button></td> </tr>`; $('#expensesTable').append(newRow); // After adding a new row, reindex all rows expenseIndex++ calculateTotal(); }); $(document).on('click', '.removeExpense', function () { $(this).closest('tr').remove(); reindexExpenses(); calculateTotal(); }); function reindexExpenses() { // Reindex each row to ensure sequential indexes $('#expensesTable tr').each(function (index) { $(this).find('input').each(function () { let field = $(this).attr('name'); if (field) { // Update the name attribute to reflect the current index var newName = field.replace(/Expenses[d+]/, `Expenses[${index}]`); $(this).attr('name', newName); } }); }); // Update the expenseIndex to reflect the current number of rows expenseIndex = $('#expensesTable tr').length; } // Calculate total expense amount function calculateTotal() { var total = 0; $('.amountInput').each(function () { var amount = parseFloat($(this).val()) || 0; total += amount; }); $('#totalAmount').text(total.toFixed(2)); // Update total amount display } // Update total amount on input change $(document).on('input', '.amountInput', function () { calculateTotal(); }); // Recalculate total on page load $(document).ready(function () { calculateTotal(); }); // Validate form before submission to ensure at least one expense $('#expenseForm').click(function (e) { var expensesCount = $('#expensesTable tr').length; if (expensesCount === 0) { Swal.fire({ icon: 'warning', title: 'No Expenses Added', text: 'At least one expense must be added.', confirmButtonText: 'OK' }); e.preventDefault(); // Prevent form submission if no expenses } }); </code>
var expenseIndex = $('#expensesTable tr').length;  // Initialize expenseIndex to the number of existing rows

// Add new expense row
$('#addExpense').click(function () {
    var newRow = `<tr>
                    <td><input type="text" name="Expenses[${expenseIndex}].Description" class="form-control" /></td>
                    <td><input type="date" name="Expenses[${expenseIndex}].ExpenseDate" class="form-control" /></td>
                    <td><input type="number" name="Expenses[${expenseIndex}].Amount" class="form-control amountInput" /></td>
                    <td><button type="button" class="btn btn-danger removeExpense">Remove</button></td>
                  </tr>`;
    $('#expensesTable').append(newRow);
    
    // After adding a new row, reindex all rows
expenseIndex++ 
    calculateTotal();
});

$(document).on('click', '.removeExpense', function () {
    $(this).closest('tr').remove();
    reindexExpenses();  
    calculateTotal();
});

function reindexExpenses() {
    // Reindex each row to ensure sequential indexes
    $('#expensesTable tr').each(function (index) {
        $(this).find('input').each(function () {
            let field = $(this).attr('name');
            if (field) {
                // Update the name attribute to reflect the current index
                var newName = field.replace(/Expenses[d+]/, `Expenses[${index}]`);
                $(this).attr('name', newName);
            }
        });
    });

    // Update the expenseIndex to reflect the current number of rows
    expenseIndex = $('#expensesTable tr').length;
}

// Calculate total expense amount
function calculateTotal() {
    var total = 0;
    $('.amountInput').each(function () {
        var amount = parseFloat($(this).val()) || 0;
        total += amount;
    });
    $('#totalAmount').text(total.toFixed(2));  // Update total amount display
}

// Update total amount on input change
$(document).on('input', '.amountInput', function () {
    calculateTotal();
});

// Recalculate total on page load
$(document).ready(function () {
    calculateTotal();
});

// Validate form before submission to ensure at least one expense
$('#expenseForm').click(function (e) {
    var expensesCount = $('#expensesTable tr').length;
    if (expensesCount === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Expenses Added',
            text: 'At least one expense must be added.',
            confirmButtonText: 'OK'
        });
        e.preventDefault();  // Prevent form submission if no expenses
    }
});

The problem I’m encountering: When users add a few rows and then remove one, the new row added later does not get the correct index. For example, if the user has rows with indexes 0 and 1, and then removes the row with index 1, a new row added will have index 2 instead of 1.

  • Implemented reindexing logic that updates the name attributes of inputs.
  • Updated expenseIndex after adding or removing rows.
    What I need help with: I need help fixing the reindexing logic so that when rows are removed, the indexes of the remaining rows are updated correctly. Any suggestions or solutions would be greatly appreciated!

2

You dont have to add index in a form name (not mandatory !)
If you need edit function using data attribute may be more usefull!

Also if you have too much needs like this i can suggest to move another library then Jquery !

Just check this one…

https://www.geeksforgeeks.org/build-an-expense-tracker-with-html-css-and-javascript/

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật