Steve Kim
Steve Kim

Reputation: 5591

.each to return value in js

Let say I have 4 div elements:

<div class="example"></div> //empty
<div class="example"></div> //empty
<div class="example">hi</div> //has content
<div class="example"></div> //empty

Then using .each, I want to assign value of either 0 (empty) or 1 (has content):

var container = {}; 

container['status'] = $('div.example').each(function(){                 
         var inside = $(this).html();

         //Check for empty
         if (typeof inside == 'undefined' || inside == '' || inside == '<br>') {                        
             var warning = 0;

         }else{
             var warning = 1;

         }  
         return warning;

       });  

console.log(container);

In this scenario, I want to get "0,0,1,0" as the returned value. How would I do this?

Upvotes: 1

Views: 58

Answers (3)

khiav reoy
khiav reoy

Reputation: 1403

container['status'] = $(selector).each(YourFunc)

Use map instead of each, then call join to join elements

container['status'] = $(selector).map(YourFunc).get().join()

Works in Jquery 1.10.2

Upvotes: 1

kukkuz
kukkuz

Reputation: 42352

Use a map function instead - see demo below:

var container = {};

container['status'] = $('div.example').map(function() {
  var inside = $(this).html();
  //Check for empty
  if (typeof inside == 'undefined' || inside == '' || inside == '<br>') {
    var warning = 0;
  } else {
    var warning = 1;
  }
  return warning;
}).get();

console.log(container);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example"></div>
<div class="example"></div>
<div class="example">hi</div>
<div class="example"></div>

Upvotes: 1

guest271314
guest271314

Reputation: 1

Use $.map() to return an array of value

var container = {}; 

container["status"] = $.map($('div.example'), function(el) {  
                        return !el.textContent.trim().length || $(el).is(":empty") 
                               ? 0 : 1
                      });

Upvotes: 2

Related Questions