Focus on a field with tabpage

Asked

Viewed 30 times

2

I am using this code, to put the embroidery in red when a field of the tab is not filled correctly, and it then gives the Focus on the nearest tab, and so on.

$.each($('input[data-required="true"]'), function () {
        if (!this.value || this.value == '') {
            e.preventDefault();
            $(this).css('border', 'red 1px solid');
            var id = $($(this).parents('.tab-pane')[0]).attr('id');
            $('[href="#' + id + '"]').trigger('click');
            $(this).focus();
            return false;
        }
    });

I’d like you to focus in the first field, for the user to already type in the field. I tried adding this line:

     $(this).focus();

But it didn’t work.

1 answer

0


What’s blocking the event .focus() to be executed is the e.preventDefault(). Follow the code set and working:

    $.each($('input[data-required="true"]'), function () {
        if (!this.value || this.value == '') {
            $(this).css('border', 'red 1px solid');
            var id = $($(this).parents('.tab-pane')[0]).attr('id');
            $('[href="#' + id + '"]').trigger('click');
            $(this).focus();
            event.preventDefault(); // Vai prevenir o submit do formulário
            return false; // Vai parar a execução do .each() 
        }
    }); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.