Reputation: 91
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
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>');
}
});
});
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>');
}
});
Upvotes: 0
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>');
}
});
});
Upvotes: 1
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>');
}
});
});
Upvotes: 0
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>');
}
});});
Upvotes: 0
Reputation: 16764
You have to initialise jquery:
$(function(){
// code here
});
and code will work:
Upvotes: 0