adding a new div to the bottom of a row that is being created on the fly

I encountered an issue where rows are created dynamically and I needed to add a div at the end of each row. Despite trying various methods, I faced difficulties as adding the div resulted in extra divs being added to all previous rows whenever a new row was inserted. My objective was to have just one cancel button assigned to each row for user ease.

In my current code, I am attempting to iterate through each row with the 'row' class and verify whether a child element with the class "cancel" exists. If not, I aim to append the cancel div. While this approach works initially, subsequent attempts fail to yield the desired outcome.

$('.row').each(function(){
 if($(".row").children(".cancel").length == 0){
    $("<div class = 'cancel'>test</div>").appendTo('.row')
}   
})

An alternate solution I experimented with involved inserting the 'cancel' div within an else statement while appending rows:

if($(".table").html().length <= 0)
 {
    $('.table').append($("<table>").append(tableheader).append(tr));

}else{
    if($(".table").html().length > 0){
        $("table").append(tr).append("<div class = 'cancel'>test</div>")

    }

}

However, the above method did not render the expected output at all.

Although one workaround could involve adding another td to the tr variable for creating a new column with the div, I am curious as to why my aforementioned approaches failed. They should have ideally worked. Kindly pardon any oversight on my part.

For better clarification, here is the jsfiddle link. It's possible that there might be an error in the code elsewhere.

An additional issue I am facing pertains to the total amount displayed in the total column. The figures are appearing as 7.5 instead of the standard dollar pricing format like 7.50. Moreover, calculating totals like selecting grilled chicken cutlet with a quantity of 3 results in 38.849999999999994 rather than the expected 38.85 even after using toFixed(2) and parseFloat. Any guidance you can provide on resolving this discrepancy would be greatly appreciated.

Answer №1

It seems like the issue lies in how you are accessing the table rows when appending the div.

$('.row').each(function(){
    if($(".row").children(".cancel").length == 0){
        $("<div class = 'cancel'>test</div>").appendTo('.row')
    }   
});

The code above always looks for the class .row while adding the div. This means that if there is a div appended to any one of the .row classes, the if condition will fail.

Solution:

To resolve this issue, utilize $(this) to access each row within the loop.

$('.row').each(function(){
    if($(this).children(".cancel").length == 0){
        $("<div class = 'cancel'>test</div>").appendTo($(this))
    }   
});

Additionally, to address your second concern regarding price, update

$(".total",$row).html(parseFloat(qnty * price));

to

$(".total",$row).html(parseFloat(qnty * price).toFixed(2));

Feel free to check out the revised Demo Fiddle.

Answer №2

Give this a shot:

$('.row').each(function(index, value){
    if($(value).children(".cancel").length == 0){
        $("<div class = 'cancel'>test</div>").appendTo(value);
    }   
});

Answer №3

  1. To achieve this, simply execute the following code: a)console.log($('.row').length)// to view the length

  2. Insert $("test").appendTo('.row') //this.code should be "$("test").appendTo($(this))"

    I believe the tips provided above will be beneficial; give it a try yourself

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 are some best practices for preventing unforeseen rendering issues when utilizing React Context?

I am encountering an issue with my functional components under the provider. In the scenario where I increase counter1 in SubApp1, SubApp2 also re-renders unnecessarily. Similarly, when I increase counter2 in SubApp2, SubApp1 also gets rendered even thou ...

When using $.getJSON and $.ajax, the expected JSON object is not being returned

Currently, I am taking on the "local weather" front-end development challenge on freecodecamp.com. However, I'm facing some challenges when it comes to making an API call to fetch weather data from various weather APIs. This particular task requires r ...

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

Real-time data refresh with AJAX on form submission

My current challenge involves updating a password change using AJAX and POST method. Typically, when I successfully change the password without Ajax, the result is displayed on a blank white page. Now, I am attempting to implement this process within a sm ...

Retrieve the Nth class of an element that has multiple classes without relying on the .attr("class") method in jQuery

Within a container with two styles, the initial nested div <div class="datacheck"> <div class="classic_div_data customdataid_305"> some values are included here </div> <div class="optiondiv"> </div> </div& ...

Cool ways to showcase HTML content in AngularJS

I am completely new to AngularJS. My goal is to display HTML content on the view using AngularJS. I initially tried using ng-model, but it displayed HTML content as a string on the view. After that, I attempted to use ng-bind-html which worked for the in ...

Employing jQuery Mobile with MVC3 for seamless auto-submit functionality

When I remove jQuery Mobile, the code works perfectly! The form: @using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" })) { @Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town") } The Javascript: & ...

What could be preventing me from exporting and applying my custom JavaScript styles?

This is my primary class import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import styles from './FoodStyles'; class Food extends Component { render () { return ( & ...

The heap limit has been reached in Github Actions, causing an allocation failure

Encountering a heap out of memory error in Github Action during the last "run: npm run build". FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory Error: Process completed with exit code 1. Showcasing the workflow file: name: ...

Unlocking the power of HTML tags in Selenium WebDriver: accessing elements like a pro

I'm working with this HTML snippet. <span class="ng-binding" ng-bind="::result.display">All Sector ETFs</span> <span class="ng-binding" ng-bind="::result.display">China Macro Assets</span> <span class="ng-binding" ng-bind ...

What is the best way to programmatically change the event tied to an element's click

<div id="filters"></div> <div id="available"> <span class="badge badge-pill" onclick="addFilter()">Label</span> </div> function addFilter(event) { document.getElementById("filters").appendChild(eve ...

The disadvantages of manipulating DOM in controllers in AngularJS

Many experts advise against performing DOM manipulations in AngularJS Controllers, but it can be challenging to fully understand why this is considered a best practice. While sources mention issues with testing and the primary purpose of controllers for di ...

Utilizing Webpack to Import GLB Models into Three.js

Just delving into the world of Webpack for the first time and I'm encountering some difficulties when trying to add my glb model. The model itself is fine, it's been used multiple times and I placed it in the public folder. I'm puzzled by th ...

Allowing a certain amount of time to pass before executing a method

I'm familiar with using setTimeout and setInterval to delay the execution of a method, but I am facing a specific issue. I am working on implementing a card game where three CPU players take turns with a 500ms delay between each turn. Below is the cod ...

Issue: Unable to locate element with the specified selector: #email

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://discord.com/register'); await page.screenshot({path: 'b.png ...

Learn how to create a registration form using Ajax, PHP, and MySQL

So far I've been working with HTML <form id="account_reg" action="reg.php" method="post"> <div id="response"></div> <div class="input"> <label>Login</> <input name="login" type="text" class=" ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

What exactly do discrete animations entail?

In the MDN animation documentation, it mentions a type of animation known as "discrete". Can you explain what this term signifies? ...

Unable to resolve the issue within Angular UI modal

Currently, I am facing an issue with displaying a modal using Angular Bootstrap UI. The modal is supposed to resolve items in the controller, but I am struggling to access those resolved items in the modal controller. $scope.showItemsInBill = function(bill ...