简体   繁体   中英

How to check whether specific items inside an array have a value? Javascript

I have a function which gets values from elements:

function getTransactionValues() {
    var o = {};
    o.reservations        = [];
    $('#custom-headers option:selected').each(function (i, selected) {
        o.reservations[i] = $(selected).val();
    });
    o.amount              = $('input[name=amount-price]').val();
    o.currency_value      = $('input[name=currency-value]').val();
    o.currency_name       = $('.currency_appendto option:selected').html();
    o.actual_amount       = $('input[name=actual-amount]').val();
    o.actual_remaining    = $('input[name=actual-remaining]').val();
    o.funds_arrival_date  = $('input[name=funds-arrival]').val();
    o.paid_to             = $('.paidto option:selected').html();
    o.checkbox            = $('.multi-transaction:checked').map(function () {
        return this.value
    }).get();
    return o;
}

Now i want to check whether amount, actual_amount and funds_arrival_date are filled. if they are i will release the disabled class from a button. i've tried

    var check_review = function () {
    var a = getTransactionValues();
    var options = [a.amount, a.actual_amount, a.funds_arrival_date];

    for(i = 0; i < options.length; i++) {
        if(options[i].length > 0) {
            $('a[name=review_button]').removeClass('disabled');
        }
        else{
            //this array is empty
            alert('There is a problem!');
        }
    }
}

$('.test').click(function() {
    check_review();
});

But it doesn't seems to be working..

Remove disabled attribute using JQuery?

Can you please look at above link, I think we should use $('.inputDisabled').prop("disabled", false);

Even if a single array element will be non empty then your code will remove the class disabled from the a . To make sure that all the elements of array are non empty and then only you want to remove the class then the way is:

for(i = 0; i < options.length; i++) {
        if(options[i].length > 0) {
            $('a[name=review_button]').removeClass('disabled');
        }
        else{
            $('a[name=review_button]').addClass('disabled');
        }
    }

Or the other way is

var check = true;
for(i = 0; i < options.length; i++) {
        if(options[i].length == 0) {
            check = false;
        }

    }

if(check ) $('a[name=review_button]').removeClass('disabled');

Try using Array.prototype.every()

if (options.every(Boolean)) {
  $("a[name=review_button]").removeClass("disabled");
} else {
  // do other stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM