0

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!

3 Answers 3

2

You can use Array#some:

return listOfInputs.some(function(e) {
    return e.val() != '';
});
Sign up to request clarification or add additional context in comments.

1 Comment

Just notice you unaccepted this answer five months later. Was there any issue?
2

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());

Comments

0

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;
}

1 Comment

This works, but is less efficient, since the forEach still continues to iterate the rest of the array, even if there was already a non-empty input found, which is kinda useless. The advantage of .some is that it exits as soon as the callback returns a truthy value, and it returns the boolean value of interest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.