How to change row number when add\delete rows - javascript

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 :)

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.

How to dynamically click a label to check entire row only?

The number of rows are dynamic so I cant fixate on the name of the row, here is the fiddle: http://jsfiddle.net/1vp29wxq/1/
$('.NameOfSensor').on("click", function () {
var tr = $(this).parents('tr:first');
var thisRow = tr.find(".rowMode");
var checkChecked = $("input[class='rowMode']:checkbox:checked");
var checkBoxes = $("input[class='rowMode']:checkbox");
if (checkChecked.length < checkBoxes.length)
{
checkBoxes.prop("checked", true);
}
else {
checkBoxes.prop("checked", false);
}
});
What I get from that is that all check boxes are selected, but I just want the ones from the row where it is clicked. Also, whatever I tried I cant seem to incorporate the 2 variables (tr and thisRow) I created, can I get some help? Also, the number of columns in which the checkboxes are, are always 6 (sometimes I just hide them).
Change your code into this:
$('.NameOfSensor').on("click", function () {
var tr = $(this).closest('tr');
var checkChecked = $(tr).find("input[class='rowMode']:checkbox:checked");
var checkBoxes = $(tr).find("input[class='rowMode']:checkbox");
if (checkChecked.length < checkBoxes.length)
{
checkBoxes.prop("checked", true);
}
else {
checkBoxes.prop("checked", false);
}
});
Your selector was wrong and got all rows.
Search for checkboxes within the clicked line:
var tr = $(this).closest('tr'); // fast alternative to `.parents('xxx:first')`
var checkChecked = $("input[class='rowMode']:checkbox:checked", tr),
checkBoxes = $("input[class='rowMode']:checkbox", tr);
DEMO: http://jsfiddle.net/1vp29wxq/2/

creating a 2 column table dynamically using jquery

I am trying to generate a table dynamically using ajax call. To simplify things i have just added my code to js fiddle here -> http://jsfiddle.net/5yLrE/81/
As you click on the button "HI" first two columns are created properly.. but some how as the td length reaches 2 . its not creating another row. The reason is that when i do find on the table elements its actually retrieving the children table elements. Can some one pls help.
I want a two column table.. Thank you.
sample code:
var tr = $("#maintable tbody tr:first");
if(!tr.length || tr.find("td:first").length >= max) {
$("#maintable").append("<tr>");
}
if(count==0) {
$("#maintable tr:last").append("<td>hi"+content+"</td>");
}
Basically the matching of descendants was allowing for great great grandchildren etc. Just needed to make the matching more specific.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5yLrE/91/
max = 2
$("button").click(function () {
var content = $('#template').html();
var $table = $("#maintable");
var tr = $table.find(">tbody>tr:last");
if (!tr.length || tr.find(">td").length >= max) {
// Append a blank row
tr = $("<tr>");
$table.append(tr);
}
tr.append("<td>hi " + content + "</td>");
});
This one always targets the last row and adds a row if it does not exists at all (or there are too many divs already) which is what I gather you intended.
I also used the templating I suggested to separate messy HTML strings from the code.
You will want to check the length of the table cells before incrementing a new table row. After you have reached your max column length, reset the row and start over.
JSFiddle
max_columns = 2;
count=0;
$("button").click(function() {
var content='column';
if(count==max_columns||!$('#maintable tr').length){
$("#maintable").append("<tr>");
count=0;
}
if(count!=max_columns)
$("#maintable tr:last").append("<td>"+content+"</td>");
else
$("#maintable tr:first").append("<td>"+content+"</td>");
count++;
});

How to increment a value of the table cells?

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);
});

Categories