-3

how to check if jQuery .each() function cant find something, then change txt value to 'default'.

$(this).closest('.filter-select__dropdown-inner').find('> .button--checkbox.button--active').each(function(i) {
    var val = $(this).val();

    if (i == 0) {
        txt = val;
    } else {
        txt = txt + ', ' + val;
    }
});

im already try

if (i == null) {
    txt = 'default';
}

but it doesnt work

Putra Fajar Hasanuddin
  • 1,101
  • 3
  • 13
  • 25
  • `i.length === 0` it doesnt work – Putra Fajar Hasanuddin Jun 30 '16 at 12:10
  • @PutraFajarHasanuddin, it might be a contextual issue. If you're trying to find the size of the array _in which_ you are iterating, you'd be much better off using: ``$(this).closest('.filter-select__dropdown-inner').find('> .button--checkbox.button--active').length``. Using ``i`` in the context you described, would return the length of the first argument, for the array item you're currently iterating over. – XtraSimplicity Jun 30 '16 at 12:13
  • Hold on, if it is empty set the text to 'default'? What text? – Taplar Jun 30 '16 at 12:13
  • 1
    Well you can try something like this as well: **[JSFiddle](https://jsfiddle.net/RajeshDixit/ku9fgLwx/)** – Rajesh Jun 30 '16 at 12:19

2 Answers2

5

Use .length in jquery to get the length

var lnt = $(this).closest('.filter-select__dropdown-inner').find('> .button--checkbox.button--active');
if(lnt.length > 0) {

lnt.each(function(i) {
    var val = $(this).val();

    if (i == 0) {
        txt = val;
    } else {
        txt = txt + ', ' + val;
    }
});

}
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63
Jayesh Chitroda
  • 4,987
  • 13
  • 18
1

make use of .length and check its empty or not.

var objcollection = $(this).closest('.filter-select__dropdown-inner').
         find('> .button--checkbox.button--active');

if(objcollection.length==0)
{
}
else
{
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263