.each() not looping all elements - jQuery

I have created a element to carry all my account elements like so:

var $account_list_j = $('#account_list');

I add dynamic elements so the structure looks like

<div id="account_list">
 <div class="card account-list-item">
  <input id="group_name_0" type="text" class="form-control name" name="username" placeholder="Account name" value="">
 </div>
 <div class="card account-list-item">
  <input id="group_name_0" type="text" class="form-control name" name="username" placeholder="Account name" value="">
 </div>
</div>

I try and loop over the dynamic elements and return false if any of them have a value less then the minimum account name length.

function accounts_name_check(params) {
    var success = true;
    $account_list_j.each(function(e) {
        if($(this).find('.name').val().length < min_account_name_length && success){
            var string = 'All Accounts must have a name of at least '+min_account_name_length+ ' characters.';
            add_error_message(string);
            $(this).find('.name').addClass('is-invalid');
            success = false;
        }
        else{
            $(this).find('.name').removeClass('is-invalid');
        }
    });
    return success;
}

It seems the the function will only check the first element in the list, then stops. The first element is the only static element (the others are populate account list div with a button). What am I doing wrong?

2 answers

  • answered 2018-11-08 08:01 madalinivascu

    You need var $account_list_j = $('#account_list .card'); to get a list

  • answered 2018-11-08 08:01 front_end_dev

    Change this line var $account_list_j = $('#account_list'); to var $account_list_j = $('.account-list-item');

    You have multiple account item list (account-list-item) not the multiple #account_list.