autofocus on input does not work.


Topic: autofocus on input does not work.

info21 pro asked 8 years ago

I noticed that the autofocus does not work for input fields, although I can see there is an attempt to make it work. I tried to load the JS in the head tag and at the body (although my app requires it in the body). I am also using webpack and loading the individual modules though requires, although I doubt that will cause a problem (and I am unable to not use webpack, so it would not matter in my case). I use chrome (latest) as well just to note that. Although above I showed how I tried it I can see where the problem is and how to fix it. Basically on line 22 of forms-basic.js is where its checking for the autoficus field, but there is a second jQuery ready event not far below it (and the entire block is already in a ready event) that then updates the text fields. This leads to it adding the active state for the autofocus field and then since its empty instantly removing it. The fix is to move Materialize.updateTextFields outside of the ready callback, and then call it first in the ready callback. Then instead of adding the active class for input[autofocus] just trigger focus (otherwise the focus state is lost). forms.js does it differently but although it can add the active class it loses the focus. so using a similar fix I did for forms-basic for forms it can fix it.
Hi, send me your code, please.

info21 pro answered 8 years ago

Here is my forms-basic.js (free version so should be alright to post here right?) You can compare this to the current version to see the differences, its basically described in my last post though. More can be cleaned up but was mostly focused on making it work.
/* FORMS */

(function ($) {
    // Text based inputs
    var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';

    // Function to update labels of text fields
    Materialize.updateTextFields = function () {
        var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';
        $(input_selector).each(function (index, element) {
            if ($(element).val().length > 0 || $(this).attr('placeholder') !== undefined || $(element)[0].validity.badInput === true) {
                $(this).siblings('label, i').addClass('active');
            } else {
                $(this).siblings('label, i').removeClass('active');
            }
        });
    };

    // Add active when element has focus
    $(document).on('focus', input_selector, function () {
        $(this).siblings('label, i').addClass('active');
    });

    $(document).ready(function () {
        // Add active if input element has been pre-populated on document ready
        Materialize.updateTextFields();
        $('input[autofocus]').trigger('focus');

        // Text based inputs
        var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';

        // Handle HTML5 autofocus
        //$('input[autofocus]').siblings('label, i').addClass('active');

        // Add active if form auto complete
        $(document).on('change', input_selector, function () {
            if ($(this).val().length !== 0 || $(this).attr('placeholder') !== undefined) {
                $(this).siblings('label, i').addClass('active');
            }
            validate_field($(this));
        });

        // HTML DOM FORM RESET handling
        $(document).on('reset', function (e) {
            var formReset = $(e.target);
            if (formReset.is('form')) {
                formReset.find(input_selector).removeClass('valid').removeClass('invalid');
                formReset.find(input_selector).each(function () {
                    if ($(this).attr('value') === '') {
                        $(this).siblings('label, i').removeClass('active');
                    }
                });

                // Reset select
                formReset.find('select.initialized').each(function () {
                    var reset_text = formReset.find('option[selected]').text();
                    formReset.siblings('input.select-dropdown').val(reset_text);
                });
            }
        });

        // Add active when element has focus
        // $(document).on('focus', input_selector, function () {
        //     $(this).siblings('label, i').addClass('active');
        // });

        $(document).on('blur', input_selector, function () {
            var $inputElement = $(this);
            if ($inputElement.val().length === 0 && $inputElement[0].validity.badInput !== true && $inputElement.attr('placeholder') === undefined) {
                $inputElement.siblings('label, i').removeClass('active');
            }
            validate_field($inputElement);
        });

        validate_field = function (object) {
            var hasLength = object.attr('length') !== undefined;
            var lenAttr = parseInt(object.attr('length'));
            var len = object.val().length;

            if (object.val().length === 0 && object[0].validity.badInput === false) {
                if (object.hasClass('validate')) {
                    object.removeClass('valid');
                    object.removeClass('invalid');
                }
            } else {
                if (object.hasClass('validate')) {
                    // Check for character counter attributes
                    if ((object.is(':valid') && hasLength && (len < lenAttr)) || (object.is(':valid') && !hasLength)) {
                        object.removeClass('invalid');
                        object.addClass('valid');
                    } else {
                        object.removeClass('valid');
                        object.addClass('invalid');
                    }
                }
            }
        };

        // Textarea Auto Resize
        var hiddenDiv = $('.hiddendiv').first();
        if (!hiddenDiv.length) {
            hiddenDiv = $('<div class="hiddendiv common"></div>');
            $('body').append(hiddenDiv);
        }
        var text_area_selector = '.materialize-textarea';

        function textareaAutoResize($textarea) {
            // Set font properties of hiddenDiv

            var fontFamily = $textarea.css('font-family');
            var fontSize = $textarea.css('font-size');

            if (fontSize) {
                hiddenDiv.css('font-size', fontSize);
            }
            if (fontFamily) {
                hiddenDiv.css('font-family', fontFamily);
            }

            if ($textarea.attr('wrap') === "off") {
                hiddenDiv.css('overflow-wrap', "normal")
                    .css('white-space', "pre");
            }

            hiddenDiv.text($textarea.val() + 'n');
            var content = hiddenDiv.html().replace(/n/g, '<br>');
            hiddenDiv.html(content);

            // When textarea is hidden, width goes crazy.
            // Approximate with half of window size

            if ($textarea.is(':visible')) {
                hiddenDiv.css('width', $textarea.width());
            } else {
                hiddenDiv.css('width', $(window).width() / 2);
            }

            $textarea.css('height', hiddenDiv.height());
        }

        $(text_area_selector).each(function () {
            var $textarea = $(this);
            if ($textarea.val().length) {
                textareaAutoResize($textarea);
            }
        });

        $('body').on('keyup keydown', text_area_selector, function () {
            textareaAutoResize($(this));
        });

    }); // End of $(document).ready

}(jQuery));

Bartłomiej Malanowski staff pro premium answered 8 years ago

@info21, please contact me at b.malanowski@mdbootstrap.com

info21 pro answered 8 years ago

The issue was easily fixed, I just wanted to inform you of the issue and a possible solution. I personally see no reason to start up an email thread?

Bartłomiej Malanowski staff pro premium answered 8 years ago

Sorry for misunderstanding! Thank you for sharing your solution!

riza answered 5 years ago

please help I want to make an autofocus input tag when opening modal. this is my code: this doesn't work


Magdalena Dembna staff premium commented 5 years ago

Unfortunately your code doesn't show. Can you create a code snippet here: https://mdbootstrap.com/snippets/ ?


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Pro
  • Premium support: No
  • Technology: General Bootstrap questions
  • MDB Version: -
  • Device: -
  • Browser: -
  • OS: -
  • Provided sample code: No
  • Provided link: No