Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for empty a field from all in jQuery

I have four fields, and I the function to return true if atleast one field has a value, if all fields don't have a value return false, How do I do this?

My try:(this doesn't work like I want)

function required_eachinput(){
    result = true;
    $('.myclass').each(function(){
        var $val = $(this).val();
        var ok = $val.each(function(){});
        alert(ok);
        if(!$val){
            $(this).css("background", "#ffc4c4");
            result = false;
        }
        $(this).keyup(function () {
            $(this).closest('form').find('input').css("background", "#FFFFEC");
        })
    });
        return result;
}
like image 798
Kate Wintz Avatar asked Jan 27 '26 01:01

Kate Wintz


1 Answers

My recommendation is:

function required_eachinput(){
    var result = '';
    $('.myclass').each(function(){
        result += $(this).val();
    });
    return result != '';
}

What it does basically is to concatenate all the values of all 4 fields (could be any number of fields). If the result is not an empty string, it means that at least of one the fields has a value. Otherwise, all are empty.

like image 99
Saeed Neamati Avatar answered Jan 28 '26 14:01

Saeed Neamati