Home:ALL Converter>Using $(this) at a method inside another method in jQuery

Using $(this) at a method inside another method in jQuery

Ask Time:2015-06-05T05:51:17         Author:Enrique Sampaio

Json Formatter

So, I'm trying to use the 'this' selector in a method inside another method, example:

$('form').submit(function(event){
   $('input').each(function(){
       if($(this).val().length < 2){
           $(this).addClass('error');
           event.preventDefault(); 
       }
   });
});

When I made that, I thought it would admit 'this' as each input, but no, the 'this' selector are associated to the form. I know that because the result is:

<form class="error" action="lorem.php" method="post">
    <input type="text" placeholder="Lorem Ipsum" name="example">
</form>

That's only an example to illustrate that when I submit a form, the class 'error' goes to the 'form' tag.

I want to know how can I call each 'input' inside the 'each' method, since 'this' seems not to work.

I hope I made my point here, if someone needs more explanation just tell me.

Thank you very much!

Author:Enrique Sampaio,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/30654821/using-this-at-a-method-inside-another-method-in-jquery
yy