Reputation: 926
Good afternoon, I'm hoping someone can help me here.
I'm quite new to jQuery
so forgive me if this is a really obvious mistake I'm making.
I've got a form which allows me to add additional fields, I have it working and I've got it so they have unique ID tags but I'd like so when I click my removeFieldTeam
it removes the specific field I have clicked on.
At the moment, it removes fields automatically from the bottom upwards.
Any help is appreciated.
Upvotes: 0
Views: 49
Reputation: 2225
Here is the updated jquery code. I tested, it works:
$(document).ready(function () {
// Set the counter value
var countTeam = 1;
$("#addFieldTeam").click(function () {
event.preventDefault();
// If there's more than 10 fields, throw an alert
if (countTeam == 10) {
alert("Only 10 fields allowed");
return false;
}
// Declaring our new div and adding the form input.
var newField = $(document.createElement('div'))
.attr({
id: "newFieldTeam" + countTeam,
class: "form-group"
});
newField.after().html(
'<label class="form-label-bold" for="fieldTeam' + countTeam + '"' + '>' +
'Team '+countTeam+'</label>' +
'<input class="form-control fullish" id="fieldTeam' + countTeam +
'" type="text">' +
'<span><a class="minuslinkreport removeFieldTeam" href="#"> - </a></span>'
);
// adding the new field to the page within the #fieldGroupTeam div
newField.appendTo('#fieldGroupTeam');
// Increase the counter by 1
countTeam++;
console.log(countTeam);
});
// Once there's no more fields to delete, throw an error.
$(document).on('click', ".removeFieldTeam", function () {
event.preventDefault();
if (countTeam < 2) {
alert("No fields to remove");
return false;
}
countTeam--
console.log(countTeam);
// Decrease the counter by 1 and remove the field.
console.log($(this).closest('div'));
$(this).closest('div').remove();
});
});
For the remove button, I changed it from id to class, and onclick I am removing the closest div.
Please test and let me know if this works.
Here is the working fiddle
Upvotes: 2