Joper
Joper

Reputation: 8219

jQuery check if two values is blank

I have three values:

var tbb = $("#total1 span").text();
var tmb = $("#total2 span").text();
var tab = $("#total3 span").text();

Each of them could be blank.

What is the better way in javascript/jquery check if two of these values is blank?

UPDATE

here is what i mean, my a bit ugly and a "lot of lines" solution

var i = 0;
            if (tab != "") {
                i++;
            }

            if (tmb != "") {
                i++;
            }

            if (tbb != "") {
                i++;
            }

            if (i >= 2) {
                //do something
            }

Any better thoughts?

Upvotes: 1

Views: 1167

Answers (8)

Dan Crews
Dan Crews

Reputation: 3637

It's been a while, but this is going to be a single-line solution for what you want.

if (((tab == '' ? 1 : 0) + (tmb == '' ? 1 : 0) + (tbb == '' ? 1 : 0)) > 1){
    // Do Something
}

Upvotes: 0

Nishu Tayal
Nishu Tayal

Reputation: 20880

Just try it.

var i = 0; 
if(tbb.length == 0 )
{  
    i++
}
 if(tmb.length == 0 )
{  
    i++
} 
if(tab.length == 0 )
{  
    i++
}  
if(i >=2)  
{
   //perform operation
}

Upvotes: 0

pimvdb
pimvdb

Reputation: 154968

var twoAreEmpty = $("#total1, #total2, #total3").find("span:empty").length === 2;

Upvotes: 1

jAndy
jAndy

Reputation: 236202

var filtered = [tmb, tbb, tab].filter(function( str ) {
    return !str.length;
});

if( filtered.length === 2 ) {
    console.log('yay, two empty values: ', filtered); 
}

Upvotes: 0

bobber205
bobber205

Reputation: 13382

if (tab == "") should be enough shouldn't it?

Does .text() ever return blank?

Upvotes: 0

Brian
Brian

Reputation: 8626

All valid answers, but forgetting about undefined :)

if(tbb === '' || tbb === null || tbb === undefined){ // do stuff };

I'd recommend making it a function which could return true/false :)

Upvotes: -1

jimbo
jimbo

Reputation: 11042

var twoblank = 
  $("#tota11 span, #total2 span, #total3 span")
    .filter(function(index){
      return !$(this).text().replace(/^\s+|\s+$/g, '');
    })
    .length === 2;

Also, you probably mean #total1, not #tota11 - just sayin.

Upvotes: 0

Naftali
Naftali

Reputation: 146360

if(tbb == null || tbb == ''){...}

And the same for the rest.

Upvotes: 1

Related Questions