Reputation: 2575
<table border="2">
<tr><td>one</td><td>two</td></tr>
<tr><td>one</td><td>two</td></tr>
<tr><td colspan="2" id="new" >add new</td></tr>
</table>
$('#new').click(function(){
$('#new').append("<tr><td>one</td><td>two</td></tr>");
})
Now if i click "add new" then this make:
one | two
one | two
add new
one two
How can i make:
one | two
one | two
one | two
add new
LIVE: http://jsfiddle.net/tg5qD/
Upvotes: 1
Views: 145
Reputation: 87073
$('#new').click(function(){
$("<tr><td>one</td><td>two</td></tr>").insertBefore($(this).parent());
});
Read about .insertBefore()
Upvotes: 1
Reputation: 1448
You can use following way.. First need to find parent tr
of the id 'new'. then we can append our new element to before parent element.
$('#new').click(function(){
$(this).parent('tr').before("<tr><td>one</td><td>two</td></tr>");
})
Upvotes: 1
Reputation: 4547
I would actually reference the add new button using $(this)
within the click event. Saves you finding the element in the DOM again.
$('#new').click(function(){
$(this).parent().before("<tr><td>one</td><td>two</td></tr>");
})
Better still if you use the .on
event object you have the flexibility to turn off this click event at a later point if you wish.
$('#new').on({
"click.addNew": function(){
$(this).parent().before("<tr><td>one</td><td>two</td></tr>");
}
})
JS Fiddle: http://jsfiddle.net/tg5qD/11/
Upvotes: 1
Reputation: 34107
demo http://jsfiddle.net/eDNH5/2/
Another Working Demo http://jsfiddle.net/eDNH5/5/
API: http://api.jquery.com/before/
Updated another way
$('#new').click(function(){
$('table tr:last').before('<tr><td>one</td><td>two</td></tr>');
})
code
$('#new').click(function(){
$('#new').parent().before("<tr><td>one</td><td>two</td></tr>");
})
Upvotes: 1
Reputation: 35572
$('#new').click(function(){
$('#new').parent('tr').before("<tr><td>one</td><td>two</td></tr>");
})
Upvotes: 2
Reputation: 1694
$('#new').click(function(){
$('#new').parent('tr').before("<tr><td>one</td><td>two</td></tr>");
})
demo : http://jsfiddle.net/tg5qD/4/
Upvotes: 1
Reputation: 8477
You might want to use prepend() insted of append()
Here is a demo : http://jsfiddle.net/tg5qD/3/
Upvotes: 1
Reputation: 10246
$('#new').on('click', function(){
$('#new').parent().before("<tr><td>one</td><td>two</td></tr>");
})
Upvotes: 1
Reputation: 74046
You can either modify your JavaScript code in the following way:
$('#new').click(function(){
$('#new').parent().before("<tr><td>one</td><td>two</td></tr>");
})
Or modify your HTML as well, to use that script.
<table border="2">
<tr><td>one</td><td>two</td></tr>
<tr><td>one</td><td>two</td></tr>
<tr id="new"><td colspan="2" >add new</td></tr>
</table>
<script>
$('#new').click(function(){
$('#new').before("<tr><td>one</td><td>two</td></tr>");
});
</script>
The second solution appends the click handler to the row instead of the cell. That way you can easily use before
(jQuery docu).
Upvotes: 1