Reputation: 267
I have the following code to add rows dynamically upon click:
<script language="javascript">
jQuery(function(){
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" name="first_name' +
counter + '"/></td><td><input type="text" name="last_name' +
counter + '"/></td></tr>');
jQuery('table.authors-list').append(newRow);
});
});
</script>
<table class="authors-list">
<tr>
<td>author's first name</td><td>author's last name</td>
</tr>
<tr>
<td>
<input type="text" name="first_name" />
</td>
<td>
<input type="text" name="last_name" />
</td>
</tr>
</table>
<a href="#" title="" class="add-author">Add Author</a>
The code works fine in jsFiddle, but when I copy it to my notepad, and try to run it from the WAMP server, it doesn't work.
Another question: how can I add a remove row button beside each row in order to remove the row upon click?
Upvotes: 0
Views: 4654
Reputation: 193261
The answer to your second question (with slightly changed code):
$(function() {
var $table = $('table.authors-list'),
counter = 1;
$('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow =
'<tr>' +
'<td><input type="text" name="first_name' + counter + '"/></td>' +
'<td><input type="text" name="last_name' + counter + '"/></td>' +
'<td><a class="remove">remove</a></td>'
'</tr>';
$table.append(newRow);
});
// Remove rows on click
$table.on('click', '.remove', function() {
$(this).closest('tr').remove();
});
});
So the best way to remove rows is to listen click events on some remove
-links and delete corresponding parent row.
Upvotes: 3
Reputation: 7618
Add the following line of code before your <script>
tag:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
This will load the jQuery library into your web page, letting you use all the functions and properties of jQuery
or $
object.
Upvotes: 1
Reputation: 527
Answer to your first question: Please provide us with further information... This problem can be caused by several reasons.
Answer to your second question:
You can append a remove button with class "remove_button" to your variable called "newRow" and add an ID to it (i.e id="remove_button_" + counter
).
When clicking on the remove button call a function which is extracting the number of the button's ID and remove the other elements with same number by using remove()
function
Upvotes: 0
Reputation: 1697
Are you sure that you have loaded JQuery correctly into your HTML file? JQuery could be loaded in JSFilde already but is maybe missing on your Project.
Upvotes: 3