Service count issue fix
November 19, 2024 ยท AI Conversations
$('.geodir-add-listing').on('click','.addmoreservice',function() {
if (serviceCount < 3) {
$("#moreservicediv").append(`
+
–
`);
serviceCount++;
}
});
if we added all 3 then delete one of them and then again click + item not added
To fix this, you should decrement `serviceCount` whenever a service is removed. Here's the updated code:
let serviceCount = 1;
$('.geodir-add-listing').on('click', '.addmoreservice', function () {
if (serviceCount < 3) {
$("#moreservicediv").append(`
<div class="service-item">
<input type="text" name="services_offered_service_name[]" id="services_offered_service_name" class="form-control">
<a href="javascript:void(0)" class="addmoreservice">+</a>
<a href="javascript:void(0)" class="removemoreservice">-</a>
</div>
`);
serviceCount++;
}
});
$('.geodir-add-listing').on('click', '.removemoreservice', function () {
$(this).closest('.service-item').remove();
serviceCount--;
});
### Key Changes:
1. **Decrement `serviceCount`:**
– In the `.removemoreservice` event, decrement the `serviceCount` variable when an item is removed.
2. **Proper class selector:**
– Used a `.service-item` class for consistency and easy identification when removing elements.
3. **Dynamic event delegation:**
– The `.on` method ensures that the events are correctly attached even for dynamically added elements.
Now, when you remove a service, the counter will update correctly, allowing you to add new services as long as the total count remains less than 3.