jQuery to loop through dynamically created elements with the same class - javascript

I have no. of div which is created dynamically in button click.
<table>
<tbody id="ProductDetail"></tbody>
</table>
In button click, some no. of div are created with Amount value.
funtion createDiv(){
$("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}
I want to loop through these dynamically created div to get Amount values in jquery.I tried below code. But its not iterating loop.
function calculateAmount(){
$('.Amount').each(function (i, obj) {
TotalAmountValue=TotalAmountValue+$(this).html();
});
}
Please anybody help me.

I got this working just fine!
$(document).ready(function(){
$("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
$("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
$("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
$("#sum").click(function()
{
var sum = 0;
$(".Amount").each(function()
{
sum += parseInt($(this).text());
});
alert(sum);
});
});
the .each iterates through all your elements that have the class Amount. Use the . selector for class and add the name.
Index represents the position, while the val is the current element.
Edit: get a local variable and set it to 0. After that, iterate through all the elements with that class and take their text. Since it is String, js will try to convert the sum variable to String. You need to parse the text to int. This is a working example.
Here is the HTML
<table>
<tbody id="ProductDetail"></tbody>
</table>
<input type="button" id="sum" value="Sum">

Try using text()
$('.Amount').each(function (i, obj) {
TotalAmountValue += parseInt($(this).text());
});

$('.Amount').each(function(index, val)
{
//do something
});

If you are calling the calculateAmount() function right after createDiv() depending on your page weight, it might happen that the DIV you create on the fly it's not written to the DOM yet and your each function inside calculateAmount() it's not triggered. I recommend adding a JS delay to give the browser the time to append the divs to the DOM. For the user, it will make no difference.
HTML
<table>
<tbody id="ProductDetail"></tbody>
</table>
JS
function createDiv(){
$("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}
function calculateAmount(){
$('.Amount').each(function (i, obj) {
TotalAmountValue += parseInt($(this).text());
});
}
createDiv();
setTimeout(function () {
calculateAmount();
}, 400);

Related

jquery function on same classes

I have a page where I have a table with a class. This table sometimes occurs multiple times on the page. I need to do the same jquery function on each instance. How do I achieve that with jquery...???
Here is my jquery:
jQuery(window).load(function () {
if(jQuery('.ezfc-summary-table tr:eq(2) td:eq(1)').text()=='1 layer'){
jQuery('.ezfc-summary-table tr:eq(5)').hide();
jQuery('.ezfc-summary-table tr:eq(6)').hide();
jQuery('.ezfc-summary-table tr:eq(8)').hide();
}
});
#devlin carnate - i'm trying to do another thing, which is to take the text from one of the td's and append it to another class (product-title), which also appears multiple times. Here is what i have tried, but it only takes the text from the first td it finds, and appends it to all the following classes.
$(document).ready(function() {
$('.ezfc-summary-table').each(function(i, obj) {
var table = $(this);
if (table.find('tr').eq(2).find('td').eq(1).text() == '1 layer') {
table.find('tr').eq(5).hide();
table.find('tr').eq(6).hide();
table.find('tr').eq(8).hide();
var getpartname = $('.ezfc-summary-table tr:eq(0) td:eq(1)').text();
$('.product-title').append('<span style="padding-left: 5px;">'+getpartname+'</span>');
}
});
});
Could you help me solve this problem also...???
Thanks in advance
You can iterate over the class assigned to the tables using jQuery $.each() and hide the rows based on whether the '1 layer' text condition is met:
$(document).ready(function() {
$('.ezfc-summary-table').each(function(i, obj) {
var table = $(this);
if (table.find('tr').eq(2).find('td').eq(1).text() == '1 layer') {
table.find('tr').eq(5).hide();
table.find('tr').eq(6).hide();
table.find('tr').eq(8).hide();
}
});
});
Here is a Fiddle Demo : https://jsfiddle.net/zephyr_hex/f45umhkp/2/

Calculate values using jquery

I am still studying jquery and I have this code in my gsp:
<g:each in="${poundList}" var="poundInstance">
<span>${poundInstance?.name}<span/>
<span class="price">${poundInstance?.price}<span/>
</g:each>
<span id="total"></span>
In my jquery:
function calculatePound() {
totals= 0;
$(".price").each (function() {
totals= totals+ parseFloat("0" + $(this).val());
});
$("#total").text(totals.toFixed(2));
}
$(document).ready(function() {
calculatePound();
});
The code above has no errors. But the problem is that the <'span id="total"'> is empty or has a value of 0.0
What I was trying to do is to calculate the price of each poundInstance and display it.
How can I make it work using this code? Or I am too far from what I want to achieve?
Thanks.
You can't use val(), the method is primarily used to get the values of form elements such as input, select and textarea. You can use text():
function calculatePound() {
var totals= 0;
$(".price").each (function() {
totals= totals+ parseFloat("0" + $(this).text());
});
$("#total").text(totals.toFixed(2));
}

What's the smartest way to select specific table elements in javascript?

I've got a table with hidden rows on it, like such
-visible-
-invisible-
-visible-
-invisible-
When I click on a table row, I want it to show the invisible row. Currently I have that using this function:
var grid = $('#BillabilityResults');
$(".tbl tr:has(td)").click(
function () {
$(grid.rows[$(this).index()+1]).toggle();
}
However, this table also hides the visible rows if I click on one of the (now visible) hidden rows.
I'd like the click function to only work on the specific visible rows. Currently all my invisible rows have the class "even" so I figured I could limit the click based on that. However, I can't seem to find the syntax to explain that to my function. How would I go about doing that? And, more importantly, is there a better way to approach this?
Use next:
$(".tbl tr:has(td)").click(
function () {
$(this).next().toggle();
}
);
And also if you have specific selector for odd or even:
$(".tbl tr.odd").click(
function () {
$(this).next().toggle();
}
);
But I think that the major help with my answer is to use next() that get you the next row, instead of the index process that you were doing.
var grid = $('#BillabilityResults');
$(".tbl tr:visible").click(
function () {
$(this).next('tr').toggle();
});
Use the NOT function to disregard the EVEN tr elements:
http://jsfiddle.net/7AHmh/
<table class="tbl">
<tr><td>one</td></tr>
<tr class="even" style="display:none"><td>two</td></tr>
<tr><td>three</td></tr>
<tr class="even" style="display:none"><td>four</td></tr>
</table>​
$(".tbl tr:has(td)").not("tr.even").click(function() {
alert("Click triggered.");
$(this).next("tr").show();
});
I guess you could check for even/odd rows with the modulus operator before calling your toggling code:
function() { // your anonymous function
if (rowNumber % 2 == 0) { // only even rows get through here
// toggle code here
}
}
I hope it helps.

How to get the values of html hidden wrapped by a div using jquery?

Im very new to javascript and jquery so please bear with me.
Here's my code: http://jsfiddle.net/94MnY/1/
Im trying to get the values of each hidden field inside the div.
I tried
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
var totalHidden = 7;
for(var i=0; i<totalHidden; i++) {
alert($("#hiddenField hidden").html());
}
});
});
but the value Im getting is null.
I also wanna know how to get the total number of html elements inside a div. In my case how am I gonna get the total number hidden field inside the div. I assigned the value of totalHidden = 7 but what if I dont know total number of hidden fields.
Please help. Thanks in advance.
$('#hiddenField hidden') is attempting to access an actual <hidden> tag that is a child of #hiddenField
Try this instead. What you want to use is the input[type=hidden] selector syntax. You can then loop through each of the resulting input fields using the jQuery.each() method.
If you want to iterate over the <input> elements and alert each value try this:
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$('#hiddenField input').each(function() {
alert(this.value);
});
});
});
http://jsfiddle.net/94MnY/8/
Here it is.
Basically, you are looking for .each(). I removed a few input fields because so many alert messages are annoying. Also added in the selector the type hidden to avoid getting your last input field.
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$('input[type="hidden"]').each(function(i){
alert($(this).attr('value'))
})
});
});
To stick to what you already have - but with few modifications:
DEMO
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
var totalHidden = $('#hiddenField input[type=hidden]').length; // get number of inputs
for(var i=0; i<totalHidden; i++) {
alert($("#hiddenField input[type=hidden]").eq(i).val());
}
});
});
You can actually just create an array of those hidden elements using query and loop through them and alert their values.
I have put a jsfiddle for you to see
http://jsfiddle.net/94MnY/4/
$(document).ready(function() {
$('input#btnDispHidden').click(function() {
$("#hiddenField input[type='hidden']").each(function(i, e){
alert($(this).val());
});
});
});
Try
$('#hiddenfield input[type=hidden]').each(function(){
alert(this.val());
});

How to iterate through an HTML table column and input the values into a Javascript array using JQuery

Let's say I have a table column with 10 rows, each with <td id="num"> and a text value.
How can I use JQuery to loop through each row in the column and input the spins into a Javascript array?
I thought the following code would do it, but it is only getting the first element:
var numArray = [];
$("#num").each(function(n){
numArray[n] = $(this).text();
});
Any ideas?
Thanks!
You can't have multiple elements with the same id. This isn't allowed because the id is used to identify individual elements in the DOM. I'd suggest giving them all the same class, which is allowed.
<td class="num">
Then this should work:
var numArray = [];
$(".num").each(function(n){
numArray[n] = $(this).text();
});
Like mcos said, selecting by id for all the tables doesn't work. There can only be one item on a page with a given id.
You can either give your table an id and do the following:
var numArray = [];
// Assuming #my-table-id is your table and you want all the tds
$("#my-table-id td").each(function(n){
numArray[n] = $(this).text();
});
Or if you don't want all the tds, use a class to identify the ones you want
var numArray = [];
// Assuming #my-table-id is your table and you added class="collect"
// to the tds you want to collect
$("#my-table-id td.collect").each(function(n){
numArray[n] = $(this).text();
});
Also stealing from others answers, the map function can also help you make your code even smaller
var numArray = $.map( $("#my-table-id td.collect"), function (td){
return $(td).text();
})
You can achieve the this with using .text(function(i, text){})
var allText = [];
$("table td").text(function(i, t){
allText.push(t);
});
Code example on jsfiddle
If you need to target a particular cell(s) you can just modify the selector.
$("table td#num").text(function(i, text){
allText.push(text);
});
With that being said, an id should be unique per dom and if you can adjust the html using a class would be the right way.
<td class="num">
some text 1
</td>
$("table td.num").text(function(i, text){
allText.push(text);
});
Example
it's advised that use don't reuse the ID but since it'll html.. it'll still work..
the jQuery ID(#) selector will only select the first match...
you can use the td[id^='num'] or td[id*='num'] or td[id$='num'] instead
use the map ..
var numArray = $("td[id^='num']").map(function(){
return $(this).text();
}).get();
This will select all the td's with ID's starting as num
See it here

Categories