Лого weborb.ru

Make a disable (not active) form button when sent to the server

Make a disable (not active) form button when sent to the server
21-06-2017 0 1204

Why you need to make the buttons inactive:

  1. To make it obvious to the user that he already pressed the button and that the form is sent
  2. To prevent the server from loading unnecessary requests, and to reduce the likelihood of any error

It is clear that you can prevent unnecessary pressing by hanging a special visualization saying that the request is accepted and the form is sent (the simplest example is to show some animated gif). However, the buttons will still remain clickable, and the most impatient users will not take advantage of this opportunity. At the same time, the form can not react to these additional pressures (the animated gif is already spinning), and the frustration of the user will only increase.

In this article I will tell you how most practical and easy to make a button inactive while waiting for a server response on the yii2 framework.

To solve this problem, we need a small js code:

 /*disable button
     ========================================================*/
    $('body').on('beforeValidate', 'form.disable-submit-buttons', function (e) {
        $(':input[type="submit"]', this).attr('disabled', 'disabled');
        $(':input[type="submit"][data-disabled-text]', this).each(function (i) {
            var $this = $(this);
            if ($this.prop('tagName') === 'input') {
                $this.data('enabled-text', $this.val());
                $this.val($this.data('disabled-text'));
            } else {
                $this.data('enabled-text', $this.html());
                $this.html($this.data('disabled-text'));
            }
        });
    }).on('afterValidate', 'form.disable-submit-buttons', function (e) {
        if ($(this).find('.has-error').length > 0) {
            $(':input[type="submit"]', this).removeAttr('disabled');
            $(':input[type="submit"][data-disabled-text]', this).each(function (i) {
                var $this = $(this);
                if ($this.prop('tagName') === 'input') {
                    $this.val($this.data('enabled-text'));
                } else {
                    $this.html($this.data('enabled-text'));
                }
            });
        }
    });

We connect this js code to our project, we specify the class disable-summit-buttons on the button we need.

 <?php
            $form = ActiveForm::begin([
                'id' => 'myForm',
                'options' => [
                    'class' => 'disable-submit-buttons'
                ],
            ]);
            ?>

I'm glad if someone helped, there will be questions, I will gladly answer the suggestions!)

You can see the demo here:  Find domain records

Add a comment

Subscribe

To our newsletter

And in the new year you will not miss anything interesting!