Joe Scotto
Joe Scotto

Reputation: 10867

Check if at least one input in array has a value using jQuery/Javascript

I'm trying to check if at least one of my inputs has a value. The code below is currently working to check if all inputs have a value, I need to just check if one in the array contains a value.

var returnValue = true;
var listOfInputs = [
    $("#entry_bg"),
    $("#entry_carbs"),
    $("#entry_bolus"),
    $("#entry_correction"),
    $("#entry_food"),
    $("#entry_notes")
];


listOfInputs.forEach(function(e) {
    if (!e.val()) {
        returnValue = false;
    }
});

if (!returnValue) {
    return false;
}

What can I do to achieve this? Any help would be great, thanks!

Upvotes: 0

Views: 1595

Answers (3)

Joe Scotto
Joe Scotto

Reputation: 10867

It seemed that the simplest solution was to just check for an element that had a value and set returnValue = true.

var returnValue = false;
var listOfInputs = [
    $("#entry_bg"),
    $("#entry_carbs"),
    $("#entry_bolus"),
    $("#entry_correction"),
    $("#entry_food"),
    $("#entry_notes")
];

listOfInputs.forEach(function(e) {
    if (e.val()) {
        returnValue = true;
    }
});

if (!returnValue) {
    openErrorModal(".entry_submit", "Add Entry", "You must fill out at least one input in order to add an entry.", "#entry_modal");
    return false;
}

Upvotes: 0

Bertrand Marron
Bertrand Marron

Reputation: 22210

You should check Array.protoype.some.

some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value

const hasAtLeastOneValue = listOfInputs.some(input => !!input.val());

Upvotes: 2

trincot
trincot

Reputation: 350242

You can use Array#some:

return listOfInputs.some(function(e) {
    return e.val() != '';
});

Upvotes: 2

Related Questions