Service count issue fix

User
let serviceCount = 1;

$('.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

Assistant
The issue arises because your `serviceCount` variable is not being updated when an item is removed. If you add three services and then delete one, `serviceCount` still thinks three services exist, so the `if (serviceCount < 3)` condition prevents adding more.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *