Mohan
Mohan

Reputation: 45

How to check each input on focus

This code is working but focus come to reversed when I click the submit button first focus on textarea box isn't focused to reverse focus on first input. How could I fix it?

           <input type="text" class="textbox texrr" name="" />             
           <input type="text" class="textbox texrr" name="" />
           <textarea class="textbox1 texrr"></textarea>
           <input type="submit" class="send" value="Send" name="submit">


    $(".send").click(function(){
        $(".texrr").each(function(index, element) {
            if($(this).val()!=""){
                $(this).removeClass('texerrbg');
                } else{
                    $(this).addClass('texerrbg').focus();
                }
        });
    });

Upvotes: 0

Views: 793

Answers (1)

d.k
d.k

Reputation: 4460

the problem is, that you deal with the jquery array which has this structure:

['input.texrr', 'input.texrr', 'textarea.texrr']

And when you traverse it with the $.each method it leaves focus on the last input in the collection which does not have any data. So you need to traverse this array backwards.

Try this:

$(".send").click(function(){
        $($(".texrr").get().reverse()).each(function(index, element) {
            if($(this).val()!=""){
                $(this).removeClass('texerrbg');
            } else{
             $(this).addClass('texerrbg').focus();
            }
        });
    });

Upvotes: 1

Related Questions