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
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.
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!
– Carlos Rocha
@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
– hugocsl
Thank you very much.
– Carlos Rocha
@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
– hugocsl