Last element in .each() set

后端 未结 3 479
陌清茗
陌清茗 2020-12-02 22:14

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 a

相关标签:
3条回答
  • 2020-12-02 22:28

    For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.

    This directly compares elements rather than just checking index numbers.

    $yourset.each(function() {
        var $this = $(this);
        if($this[0] === $yourset.last()[0]) {
            //$this is the last one
        }
    });
    
    0 讨论(0)
  • 2020-12-02 22:32

    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');
              }
          }
    });
    
    0 讨论(0)
  • 2020-12-02 22:44

    A shorter answer from here, adapted to this question:

    var arr = $('.requiredText');
    arr.each(function(index, item) {
       var is_last_item = (index == (arr.length - 1));
    });
    

    Just for completeness.

    0 讨论(0)
提交回复
热议问题