jQuery = Focus with this

Asked

Viewed 31 times

1

In:

var form = $('body div#contato section.contato');

if ($(form).find('#nome').val()=='') {
  alert ('Preencha nome');
  $(this).focus();
  return false;
};

What is the correct way to call the this?

he issues the alert but it does not make the Focus()

1 answer

1


If that’s all you do

    var form = $('body div#contato section.contato');

    if ($(form).find('#nome').val() == '') {
        console.log(this);
    };

You’ll see that what the console returns is

inserir a descrição da imagem aqui

In other words, it returns the browser window itself, because the this is not the form nor the #nome. If you want Focus to go to the #nome put as below.

inserir a descrição da imagem aqui

var form = $('body div#contato section.contato');

if ($(form).find('#nome').val() == '') {
    alert('Preencha nome');
    $('#nome').focus();
};
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<div id="contato">
    <section class="contato">
        <input tipe="text" id="nome">
    </section>
</div>

  • I had understood that, if I am inside an if, the if element would be this. But it makes sense not to be because it’s just a condition and we’re NOT modifying the element! I get it. Thank you!

  • @Carlosrocha yes o if, is a boolean function, normally it is Treu, but it can be False, qq way, this could not be the form or in the #name, so returns the window itself, even being within the condition

  • Thank you very much.

  • @Carlosrocha no problem, young man! Whenever you have questions about these things, put a console.log(this) to see what is coming back, it helps you understand things, whenever you build a function you give a console.log to keep track of things. abs

Browser other questions tagged

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