How to increment a value of the table cells? - javascript

I can't understand how to increment a value of the table cells like: 1,2,3 etc?
My code:
$('#table').each(function(i){
$(this).find('td:nth-child(1)').text(i);
});
Please, look at the full example.

I think this is what you want:
var i = 1;
$('#table').find('td:nth-child(1)').each(function()
{
$(this).text(i++);
});
Or simpler:
$('#table').find('td:nth-child(1)').each(function(i)
{
$(this).text(i + 1);
});

$('#table tr td:first-child').each(function(i){
$(this).text(i+1);
});

Related

How to style table's content?

I create table dynamically:
function createResultsTable(data) {
var table = $('<table id="tblResultsList">');
var tr;
var td;
$.each(data.d.foundItems, function(i, item) {
var button = $('<button/>', {
text: item.code,
click: function () { CellClicked(item.x,item.y,"") }
});
i % 3 === 0 && (tr = $('<tr>').appendTo(table));
tr.append('<td>').prepend(button).end();
});
$('#rstSearch').append(table);
}
Here how it looks in the view now:
Here is the Fiddle.
Here is the desired look of the content:
Here is the Fiddle.
But I am stuck. I don't know how to move to the center content and make it quadratic.
I have changed your logic a little:
td = $('<td>').appendTo(tr)
button.appendTo(td);
and have added some styles. Here is the working fiddle: https://jsfiddle.net/o2gxgz9r/14666/
If you want to make tds square, here is the solution: https://stackoverflow.com/a/22835903/6053654
Feel free to ask if anything isn't clear.
That line is wrong:
tr.append('<td>').prepend(button).end();
What it actually does is append '<td>' and button to tr.
That's because the return value of append is tr, not the new td tag.
What you could do instead is:
$('<td>').append(button).appendTo(tr);
It will be better to read more about handlebars. In this files you can read real html and load it dynamically. This is the link. You can install hadlebars with npm install handlebars.
for arrange your content:
var arr = [{"id":1,"name":"Mike"},{"id":2,"name":"Tom"},{"id":3,"name":"Herman"},{"id":4,"name":"Ursula"},{"id":5,"name":"Sam"},{"id":6,"name":"Jenny"},{"id":7,"name":"Helga"},{"id":8,"name":"Nikolas"},{"id":9,"name":"Surgen"},{"id":10,"name":"Jorg"}];
var table_str='<table id="tblResultsList" border="1"></table>';
$('#rstSearch').append(table_str);
var index=0;
var index_total=0;
var row_str='';
for(key in arr){
index++;
index_total++;
if(index==1){
row_str='<tr>';
};
row_str+='<td><input data-id="'+arr[key].id+'" class="my-btn" type="button" value="'+arr[key].name+'"></td>';
if(index==4){
row_str+='</tr>';
index=0;
$('#tblResultsList').append(row_str);
row_str='';
}
if(arr.length==index_total){
row_str+='</tr>';
$('#tblResultsList').append(row_str);
}
};
var btn_max_width = 0;
$('.my-btn').each(function(){
var test_width=$(this).outerWidth(true);
btn_max_width = Math.max(btn_max_width, test_width);
});
$('.my-btn').css({'width':btn_max_width, 'height':btn_max_width});
$('.my-btn').click(function(){
var id=$(this).attr('data-id');
alert(id);
});
like this:

JQuery: Finding a way to name cloned input fields

I'm not the best at using jQuery, but I do require it to be able to make my website user-friendly.
I have several tables involved in my website, and for each the user should be able to add/delete rows. I created a jquery function, with help from stackoverflow, and it successfully added/deleted rows. Now the only problem with this is the names for those input fields is slightly messed up. I would like each input field to be an array: so like name[0] for the first row, name[1] for the second row, etc. I have a bunch of tables all with different inputs, so how would I make jQuery adjust the names accordingly?
My function, doesn't work completely, but I do not know how to go about changing it.
My Jquery function looks like:
$(document).ready(function() {
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
clone.find("select").val('');
clone.find('input').each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
clone.find('select').each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
tr.after(clone);
});
$("body").on('click', '.delete_row', function() {
var rowCount = $(this).closest('.row').prev('table').find('tr.ia_table').length;
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
if (rowCount > 1) {
tr.remove();
};
});
});
I also created a jsFiddle here: https://jsfiddle.net/tareenmj/err73gLL/.
Any help is greatly appreciated.
UPDATE - Partial Working Solution
After help from a lot of users, I was able to create a function which does this:
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
clone.find("select").val('');
clone.find('input').each(function() {
var msg=$(this).attr('name');
var x=parseInt(msg.split('[').pop().split(']').shift());
var test=msg.substr(0,msg.indexOf('['))+"[";
x++;
x=x.toString();
test=test+x+"]";
$(this).attr('name', test);
});
clone.find('select').each(function() {
var msg1=$(this).attr('name');
var x1=parseInt(msg1.split('[').pop().split(']').shift());
var test1=msg1.substr(0,msg1.indexOf('['))+"[";
x1++;
x1=x1.toString();
test1=test1+x1+"]";
$(this).attr('name', test1);
});
tr.after(clone);
});
A working jsFiddle is here: https://jsfiddle.net/tareenmj/amojyjjn/2/
The only problem is that if I do not select any of the options in the select inputs, it doesn't provide me with a value of null, whereas it should. Any tips on fixing this issue?
I think I understand your problem. See if this fiddle works for you...
This is what I did, inside each of the clone.find() functions, I added the following logic...
clone.find('input').each(function(i) {
// extract the number part of the name
number = parseInt($(this).attr('name').substr($(this).attr('name').indexOf("_") + 1));
// increment the number
number += 1;
// extract the name itself (without the row index)
name = $(this).attr('name').substr(0, $(this).attr('name').indexOf('_'));
// add the row index to the string
$(this).attr('name', name + "_" + number);
});
In essence, I separate the name into 2 parts based on the _, the string and the row index. I increment the row index every time the add_row is called.
So each row will have something like the following structure when a row is added...
// row 1
sectionTB1_1
presentationTB1_1
percentageTB1_1
courseTB1_1
sessionTB1_1
reqElecTB1_1
// row 2
sectionTB1_2
presentationTB1_2
percentageTB1_2
courseTB1_2
sessionTB1_2
reqElecTB1_2
// etc.
Let me know if this is what you were looking for.
Full Working Solution for Anyone Who needs it
So after doing loads and loads of research, I found a very simple way on how to do this. Instead of manually adjusting the name of the array, I realised that the clone method will do it automatically for you if you supply an array as the name. So something like name="name[]" will end up working. The brackets without any text has to be there. Explanation can't possible describe the code fully, so here is the JQuery code required for this behaviour to work:
$(document).ready(function() {
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
tr.after(clone);
});
$("body").on('click', '.delete_row', function() {
var rowCount =
$(this).closest('.row').prev('table').find('tr.ia_table').length;
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
if (rowCount > 1) {
tr.remove();
};
});
});
A fully working JSfiddle is provided here: https://jsfiddle.net/tareenmj/amojyjjn/5/
Just a tip, that you have to be remove the disabled select since this will not pass a value of null.

Selecting a table data using javascript/jquery

Hi i am new to javascript and jquery.I just like to know if there is any way of selecting a table data using this format:
$("#myTable").row[index1][index2];
where index1 is row index, index2 is column. Anything similar is fine too.
Try this : you can use .eq() in jQuery to traverse through tr and td with specified index
var td = $("#myTable").find('tr:eq('+index1+')').find('td:eq('+index2+')');
var data = $(td).text();// you can use .html() if you need html inside td
Try This:
$(function(){
$('input').click(function()
{
var t= $(this).attr('class');
var text= $('.time'+t).text();
alert(text);
});
$('td').click(function()
{
var index = this.cellIndex;
alert($('tr:first').find('td').eq(index).text());
});
});
http://jsfiddle.net/oL4pfgda/
It will iterate your table cells and print the values-
$("#myTable>tr>td").each(function () {
var cell_value = $(this).html();
alert(cell_value);
})

How to change row number when add\delete rows

I have integrated add row and delete row functionality in my table. If i add row second row number is also 1. I need to change number of each row as per every add and delete like 1, 2 etc.
I used the code from this fiddle http://jsfiddle.net/MJGV2/6/.
How to achieve this? Any help would be appreciated. Thanks.
You can add this:
var renum = 1;
$("tr td strong").each(function() {
$(this).text(renum);
renum++;
});
See this Fiddle demo.
There are a lot of errors in your code - for example all id needs to be unique and you should fix this.
For example, you can add call recalculate function, like this:
function recalculate() {
var i = 1;
$(".numberRow").each(function() {
$(this).find("strong").text(i++);
});
}
Where numberRow is css class on td, where store number of row.
I add this in your jsfiddle example
There were lot of things missing in your code. i have tuned everything properly
JS CODE:
$("input[type='button'].AddRow").on('click',
function () {
if ($(this).val() == 'Delete') {
trSet = $(this).closest('tr').nextAll();
currIndex = $(this).closest('tr').find('td span').html();
$(this).closest('tr').remove();
trSet.each(function () {
$(this).find('td span').html(currIndex);
currIndex++;
});
count = currIndex - 1;
} else {
var $tr = $(this).closest('tr').clone(true);
var $input = $tr.find('input.startdatum');
++count;
$tr.find('td span').html(count);
$(this).val('Delete');
var id = 'datepicker' + count;
$input.attr('id', id).data('index', count);
console.log(count);
$tr.appendTo($(this).closest('table'));
setdatepicker();
}
});
LIVE DEMO:
http://jsfiddle.net/MJGV2/14/
Happy Coding :)

Get Sum of 2nd <td> in every <tr> in Table

I want to calculate the sum of the 2nd <td> item in each of the rows and sum the total into my div.
My JS is as follows
$('.table tbody tr:gt(0)').each(function () {
var mixTotal = parseInt($(this).find('td:nth(2)').html());
// Add total to div
$('.totals').text(mixTotal);
});
DEMO HERE http://jsfiddle.net/5pnMh/1/
My Html is a standard HTML table, which contains a thead tbody and tfoot.
I can't seem to get it to work. I can get each value but not sure how to add them.
Looking for some help
var mixTotal = 0;
$('tbody tr').each(function () {
mixTotal += parseInt($(this).find('td:eq(1)').text(),10);
});
$('.totals').html(mixTotal);
jsFiddle
Your last row of numbers will not be included in the TOTAL because it is a <tfoot>. Please also note that just because your first row is a <thead>, you may not leave out the <tr></tr> tags.
I think is better store the result in variable and after loop append it to div.
// Set global var
var mixTotal = 0;
$('.table tbody tr').each(function () {
// Just add the number
mixTotal = mixTotal+parseInt($(this).find('td:nth-child(2)').html());
});
// And finally, add total to div
$('.totals').text(mixTotal);
http://jsfiddle.net/5pnMh/3/
If you will replace :nth(2) to a :nth-child(2), your code may partly works.
If you're looking to sum the values in the second column, try this:
var mixTotal = 0;
$('.table tbody tr').add('.table tfoot tr').each(function () {
mixTotal += parseInt($(this).find('td:eq(1)').text(), 10);
});
$('.totals').text(mixTotal); // Add total to div
jsFiddle example
use this code if you got decimal numbers
var mixTotal = 0;
$('tbody tr').each(function () {
mixTotal += parseFloat($(this).find('td:eq(1)').text(),10);
});
$('.totals').html(mixTotal);
See Demo
var mixTotal = 0;
$('#your_table_id tbody tr').each(function () {
mixTotal = mixTotal + (isNaN(parseInt($(this).find('td:eq(1)').text(), 10)) ? 0 : parseInt($(this).find('td:eq(1)').text(),10))
});
$('.totals').html(mixTotal);
if u have both types of values like text or nan value

Categories