user3514095
user3514095

Reputation: 91

I can't append rows into table using jQuery

I can't add rows into table using jQuery. I want to insert rows into table with id myTable

My code is

  <script src="js/jquery.js" type="text/javascript">
  </script>
  <script language="javascript">
  $('#covered').on('change', function () {
  var v = this.value;
  for (var i = 0; i < v; i++) {
    $('#myTable').append('<tr><td>new added row' + i + '</td><td> col 2</td></tr>');
    }
   });
  </script>

<table id='myTable'>
<tr>
    <td>col 1</td>
    <td>col 2</td>
</tr>
</table>
<select name="covered" id="covered">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

Can anybody help me?

Upvotes: 0

Views: 1368

Answers (5)

Jai
Jai

Reputation: 74738

You have to wrap your code within doc ready block:

$(function(){
    $('#covered').on('change', function () {
       var v = this.value;
       for (var i = 0; i < v; i++) {
           $('#myTable').append('<tr><......</td></tr>');
       }
    });
});

Demo with doc ready


And there is one more way if you delegate your event to document then doc ready block is not needed but i will not recommend you to do it because it is very slow in performance wise.

    $(document).on('change', '#covered', function () {
       var v = this.value;
       for (var i = 0; i < v; i++) {
           $('#myTable').append('<tr><......</td></tr>');
       }
    });

Demo with delagated @ document

Upvotes: 0

Joakim M
Joakim M

Reputation: 1803

Works fine (even though you add two rows at a time) if you add document ready.

$(document).ready(function (){

     $('#covered').on('change', function () {
  var v = this.value;
  for (var i = 0; i < v; i++) {
    $('#myTable').append('<tr><td>new added row' + i + '</td><td> col 2</td></tr>');
    }
   });
});

JSFIDDLE

Upvotes: 1

Felix
Felix

Reputation: 38112

Try to wrap your code inside DOM ready handler $(document).ready(function() {...}); or shorter form $(function(){...}); to make sure all of your DOM elements have been loaded properly before executing your jQuery code:

$(function() {
    $('#covered').on('change', function () {
        var v = this.value;
        for (var i = 0; i < v; i++) {
            $('#myTable').append('<tr><td>new added row' + i + '</td><td> col 2</td></tr>');
        }
     });
});

Fiddle Demo

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

Write the code in DOM ready:

$(document).ready(function(){
$('#covered').on('change', function () {
  var v = this.value;
  for (var i = 0; i < v; i++) {
    $('#myTable').append('<tr><td>new added row' + i + '</td><td> col 2</td></tr>');
   }
});});

Demo

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16764

You have to initialise jquery:

$(function(){
   // code here
});

and code will work:

http://jsfiddle.net/2UvFT/

Upvotes: 0

Related Questions