jquerybitrix

How to avoid double click actions in ajax


My function sends 2 actions after a customer makes a double click. Is it possible to modify my function to avoid it?

function createIt() {
    var comment   = $('textarea[name="comment"]').val();
    if (!comment) {
        $('#comment_error').append("Write a comment");
        return false;
    }
    BX.ajax.runComponentAction('register:feedback',
    'createIt', {
        mode: 'class',
        data: {
            post: {
                COMMENT: comment,
            }
        },
    }).then(function (response) {
        if (response.status == 'success') {
            $('.formAction').hide();
            $('input[name="go"]').trigger('click');
        } else {
            alert(response.errors);
        }
    });
};

My code works perfectly if a customer clicks once, but after he uses a double click, the code creates 2 records.

I updated the code.

Html part looks like this

<div class="formAction">
    <form method="post" action="">
        <input type="hidden" name="AJAX_CALL" value="Y">
        <div class="mt-2">
            <div class="crm-entity-stream-content-event-title">
                Add new question
            </div>
        </div>
        <div class="mt-2">
                <textarea class="crm-entity-widget-content-textarea" name="comment" required=""></textarea>
                <div id="comment_error" style="color: red;"></div>
        </div>
        <div class="ui-btn-container ui-btn-container-center">
            <button type="button" name="add_it" id="add_it" value="" onclick="createIt()" class="ui-btn ui-btn-secondary">
                ADD
            </button>
        </div>
    </form>
</div>

Solution

  • One way to prevent an errant second click is to disable the element on the first click. For example, consider this sequence of events:

    function createIt() {
      // disable the button
      $('#add_it').prop('disabled', true);
    
      // the rest of your logic, then...
      BX.ajax.runComponentAction('register:feedback',
        /* etc. */
      }).then(function (response) {
        // within your callback handler, after your existing logic, enable the button:
        $('#add_it').prop('disabled', false);
      });
    };
    

    You'll want to make sure you account for error handling, etc. so the button isn't left in a disabled state when it shouldn't be. But overall the idea is simply to disable the button while the operation is taking place.

    You could take the UX a step further and replace the button (or at least the button's contents) with some visual indicator that an operation is being performed so the user is aware of what's going on and why the button has changed.