Jean B Jean B - 6 months ago 23
Javascript Question

Logical And/Or Operator - Unexpected end Result

I am a little embarrassed, but I don't understand why this piece of code is not behaving as expected.

Looking at the debugger and console log, the length is 1, and the innerText = 'No record found.' I was expecting the if statement to be executed, but the else statement is executed instead. To be sure, I logged the innerText and tr.length, and the result is 'No record found.' and 1 respectively. What am I not getting here?

var tr = $('.users').find('tr');
if (tr.length === 1 && ((tr[0].innerText === 'No record found.')
|| (tr[0].innerText === 'No matching records found')
|| (tr[0].innerText === ''))) {
//console.log('no record found is displayed.');
$('.customTableInfo').addClass('DisplayNone').removeClass('Display');
$('.customEntries').addClass('DisplayNone').removeClass('Display');
$('.itemPerPageLabel').addClass('DisplayNone').removeClass('Display');
$('.customPaging').addClass('DisplayNone').removeClass('Display');
} else {
console.log(tr[0].innerText);
$('.customTableInfo').addClass('Display').removeClass('DisplayNone');
$('.customEntries').addClass('Display').removeClass('DisplayNone');
$('.itemPerPageLabel').addClass('Display').removeClass('DisplayNone');
$('.customPaging').addClass('Display').removeClass('DisplayNone');
}

Answer

maybe you need to use trim(); to avoid white spaces

if (tr.length === 1 && ((tr[0].innerText.trim() === 'No record found.') 
   || (tr[0].innerText.trim() === 'No matching records found') 
   || (tr[0].innerText.trim() === ''))) {

and for this code

   $('.customTableInfo').addClass('DisplayNone').removeClass('Display');                     
   $('.customEntries').addClass('DisplayNone').removeClass('Display');                   
   $('.itemPerPageLabel').addClass('DisplayNone').removeClass('Display');              
   $('.customPaging').addClass('DisplayNone').removeClass('Display');

you can simplify it

$('.customTableInfo ,.customEntries , .itemPerPageLabel ,.customPaging').addClass('DisplayNone').removeClass('Display');