1

I need to add rows to a table dynamically when the command was given by the user to add them to the end of a printed rows. But the number of columns must add for a particular row vary by table to table.

The number of columns should add is getting dynamically to each table. So the printed number of columns must vary time to time. This is the code I used.

 $(document).ready(function(){



 $("#anc_add").click(function(){ //This is the ID of the button where user gives the command to add rows.


 var Total=$("#NumberOfColumns").val(); //This is the number of input boxes I must add to that row......


  $('#tbl1 tr').last().after(

  '<tr><td>Static Content ['+cnt+']</td><td><input type="text" name="txtbx'+cnt+'"  value="'+cnt+'">;

  ); // I need to print the given(Total) number of input boxes instead of printing textboxes like this.

   cnt++;
  });



 });

Could anyone please suggest me a way to do this. Thank you so much.

3 Answers 3

1

This will loop the total number of inputs you want to add.

$("#anc_add").click(function(){ //This is the ID of the button where user gives the command to add rows.


 var Total=$("#NumberOfColumns").val();

 var rowElem = $('<tr>').append(
    $('<td>').html('Static Content ['+cnt+']')
 );

for(var i = 0; i < Total; i++) {
  rowElem.append(
     $('<td>').html('<input type="text" name="txtbx'+cnt+'"  value="'+cnt+'">')
  ) 
  cnt++;
}

  $('#tbl1 tr').last().after(
      rowElem
  );
  });



 });
Sign up to request clarification or add additional context in comments.

1 Comment

Wow... This is awesome... And I simply understood this too... :):) It works as I need. Thank you so much for replying KungWaz.
0

Try this:

$('#my_table > tbody > tr').eq(i-1).after(html);

or

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

2 Comments

Hi thank you for replying :) But how can I print when the number of columns are dynamic to add rows?
Are you try another one?
0

A suggestion :

// What you want your new rows to be filled with :

var defaultValues = {
    'col0' : 'val0',
    'col1' : 'val1',
    'col2' : 'val2'
};

// A "template", which could be inside the HTML, to keep the code clear, i.e
// out of loops and if possible out of JavaScript.

var rowTemplate =
    '<tr>' +
        '<td>{{col0}}</td>' +
        '<td>{{col1}}</td>' +
        '<td>{{col2}}</td>' +
    '</tr>';

var oldNbRows = ...,
    newNbRows = ...;

// Only select the table once, unless it is dynamically created / deleted.

var $table = $( '#myTable' );

// Add extra rows :

for( var i = 0, maxI = newNbRows - oldNbRows; i < maxI; ++i )
{
    var html = rowTemplate;

    for( var key in defaultValues )
    {
        html.replace( '{{' + key + '}}', defaultValues[key] );
    }

    $table.children( 'tr' ).last().after( html );
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.