Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

jquery - Last element in .each() set

I have an issue, where by I am doing a simple form validation, that needs some custom stuff that the validation plugin could not do for me. Basically, I have a name, email and message field, all are required, but only email is really validated, the others just need to check if theyre not empty. Here is my current code:

$("#contactMe form").submit(function() {
    var email = $('.requiredEmail').val();
    if(email != 0)  {
        if(isValidEmailAddress(email))  {
            $('.requiredText').each(function() {
                thisVal = $(this).val();
                var $this = $(this);
                if(thisVal != 0) {
                    console.log('Valid Field: '+thisVal);
                    if ($(this) == $(this).parent(':last')) {
                        console.log('Last field, submit form here');
                    }
                }
            });
        } else {
            console.log('Email Not Valid');
        }
    } 
    return false;
});

Just to explain, I am first checking the email address is valid via the isValidEmailAddress function, which is working. Then I am going through using each(), all the requiredText fields and checking if theyre not empty. When I get to the last requiredText field, I want to submit the form using post or whatever.

if ($(this) == $(this).parent(':last')) { What I have there is obviously incorrect but I am not sure what can be used to check if it is the last in the each result set, and perform an action if true.

Can anybody help me out here?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

each passes into your function index and element. Check index against the length of the set and you're good to go:

var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
      thisVal = $(this).val();
      if(parseInt(thisVal) !== 0) {
          console.log('Valid Field: ' + thisVal);
          if (index === (length - 1)) {
              console.log('Last field, submit form here');
          }
      }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...