Reputation: 1043
I find two bugs at here:
HTML
<div id="add_form">
<table>
<tr>
<td><input type="text" value="1"/></td>
<td><div class="remove"><a href="#" class="removeclass">Remove</a></div></td>
</tr>
<tr>
<td><input type="text" value="2"/></td>
<td><div class="remove"><a href="#" class="removeclass">Remove</a></div></td>
</tr>
<tr>
<td><input type="text" value="3"/></td>
<td><div class="remove"><a href="#" class="removeclass">Remove</a></div></td>
</tr>
</table>
</div>
<a href="#" id="add_field">Add</a>
JQuery
$(document).ready(function() {
var MaxInputs = 99;
var InputsWrapper = $("#add_form table");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<tr><td><input type="text" value="' + x + '"/></td><td><div class="remove"><a href="#" class="removeclass">Remove</a></div></td></tr>');
x++;
}
return false;
});
$("body").on("click",".removeclass", function(e) {
if( x > 1 ) {
$(this).closest('tr').remove();
x--;
}
return false;
})
});
Upvotes: 0
Views: 219
Reputation: 7666
I have updated the fiddle that you created. http://jsfiddle.net/hxbc7/12/
There was a mistake in your code that I rectified.
Instead of this line
var InputsWrapper = $("#add_form table");
it should be
var InputsWrapper = $("#add_form table tr");
Upvotes: 1
Reputation: 25537
change the code like this
$(document).ready(function() {
var MaxInputs = 99;
var InputsWrapper = $("#add_form table");
var AddButton = $("#add_field");
var x = $("input[type=text]").length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
x++;
$(InputsWrapper).append('<tr><td><input type="text" value="' + x + '"/></td><td><div class="remove"><a href="#" class="removeclass">Remove</a></div></td></tr>');
}
return false;
});
$("body").on("click",".removeclass", function(e) {
if( x >= 1 ) {
$(this).closest('tr').remove();
x--;
}
return false;
})
});
Upvotes: 0
Reputation: 15403
Try this: Count the FieldCount value and append to the textbox.
$(document).ready(function() {
var MaxInputs = 99;
var InputsWrapper = $("#add_form table");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=3;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<tr><td><input type="text" value="' + FieldCount + '"/></td><td><div class="remove"><a href="#" class="removeclass">Remove</a></div></td></tr>');
x++;
}
return false;
});
$("body").on("click",".removeclass", function(e) {
if( x > 1 ) {
FieldCount--;
$(this).closest('tr').remove();
x--;
}
return false;
})
});
Upvotes: 0