0

Check if atleast one field is not empty in PHP

is very equal to this question. This is just how to do it in javascript.

When you click on #submit it should check atleast one of these fields:

input[name=weight], input[name=size_1], input[name=size_2], input[name=size_3]

are filled, and not empty. If all of them are empty, it should alert("Please fill one of the fields")

Update: forgot to mention that if the fields are 0 it should not be counted as filled.

How can i do this? I tried copy over from php, but i get stuck on the foreach loop

3 Answers 3

3

You could do this very easily with the filter method:

var filledFields = $('input[name=weight], input[name=size_1], input[name=size_2], input[name=size_3]')
    .filter(function() {
        return !!this.value && this.value !== '0'; // remove if value is empty or 0, keep otherwise
    });

if (filledFields.length) {
    // at least one element has a value set
} else {
    // no fields have values set
    alert("Please fill one of the fields")
}

What this does:

  1. Selects all the elements you want to check
  2. Runs the filter method: if you return true, the element will be kept; if you return false, it will be removed from the selection
    • !!this.value is true if the value is a non-empty string and otherwise is false
  3. We then check the length property of the selection. If it is not 0, at least one element has a non-empty value. If it is 0, they are all empty.

See:

Sign up to request clarification or add additional context in comments.

1 Comment

I forgot to mention if its 0 it should not be counted as filled
0
if (!$("input[name=weight]").val() && !$("input[name=size_1]").val() && !$("input[name=size_2]").val() && !$("input[name=size_3]").val()){
    alert('Please fill one of the fields');
}

Comments

0
$('#my-form').submit(function() {
    var fields = $(this).find('input[name=weight]', 'input[name=size_1]', 'input[name=size_2]', 'input[name=size_3]');
    if (!$fields.filter(function() { return !!$(this).val(); }).length) {
        alert('Please fill one of the fields');
        return false;
    }
});

Comments

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.