-2

I am using JQuery.each to iterate on some items, but I want to know when to stop.

Here is my code for now:

$j(".form-builder").each(function(){
  data_json+='{ "type":"'+$j(this).attr("type")+'"';
  // IF LAST ITERATION
  // data_json += '}';
  // ELSE
  //data_json+='},';
});

How could I figure out whether it's the last iteration or not ?

hasan.alkhatib
  • 1,509
  • 3
  • 14
  • 28
  • 1
    possible duplicate of [Last element in .each() set](http://stackoverflow.com/questions/4006822/last-element-in-each-set) – isherwood Sep 17 '14 at 14:37
  • 3
    Why are your trying to build JSON manually instead of using `JSON.stringfy`? If you do I the right way you don't have to know which is the last iteration. – Felix Kling Sep 17 '14 at 14:37
  • @isherwood: Agreed the question, as asked, is a dupe, but only because the OP is asking the wrong question. The question should be how to build a json string from a bunch of html elements (which might also be a dupe). – Matt Burland Sep 17 '14 at 15:49

3 Answers3

5

The first parameter to the callback in each is the index in the array. You could compare this to the length of your array.

However, since you appear to be trying to build a json string, I would just build a javascript object and then JSON.stringify it and save you the trouble.

Example:

var arr = [];
$j(".form-builder").each(function(){
    arr.push({ type: $j(this).attr("type") });
});
var data_json = JSON.stringify(arr);

To demonstrate that this will produce the same result (save some white space which isn't significant) as manually building strings (and as an excuse to use the new snippet function):

$j = $;
// Built as an array of objects and then stringify
var arr = [];
$j(".form-builder").each(function(){
    arr.push({ type: $j(this).attr("type") });
});
var data_json = JSON.stringify(arr);
alert("built as an array: " + data_json);

// Built with string concat
var items = $j(".form-builder");
var count = items.length;
data_json = "[";
items.each(function(i){
  data_json+='{ "type":"'+$j(this).attr("type")+'"';
  if (i<count -1) {
     data_json+='},';
  }
  else {
     data_json += '}';
  }
});
data_json += "]";
alert("built with string concat: " + data_json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-builder" type="foo"></div>
<div class="form-builder" type="bar"></div>
<div class="form-builder" type="la"></div>
<div class="form-builder" type="lala"></div>
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • I tried to do this, but I'm using it for a "Visualforce Page", it has it's own front end language and there are many field that generated automatically. That's why I want to iterate on items with specific class. – hasan.alkhatib Sep 17 '14 at 14:39
  • 2
    @HasanKhatib This still works only with items of `form-builder` class. The change here is in building the JSON string the RIGHT way (not manually). – Mike Brant Sep 17 '14 at 14:40
  • @HasanKhatib: Huh? I don't see how that makes manually building a json string better than just building a javascript object. It's rarely a good idea to try and manually build a json string yourself. – Matt Burland Sep 17 '14 at 14:40
  • @mike-brant Yes I want it only with items of "form-builder", I want to save the data of these specific items. – hasan.alkhatib Sep 17 '14 at 14:42
  • 1
    @HasanKhatib: As you can see, the line `$j(".form-builder").each(function(){` hasn't changed at all. It's still iterating over elements with class `form-builder`. – Felix Kling Sep 17 '14 at 14:44
  • @HasanKhatib This solution does that. Note the `.form-builder` selector which is exactly the same as in your question. I am not sure if you are grasping that the only difference between the code in your question and in this answer, is that this answer builds the JSON string in the proper manner. – Mike Brant Sep 17 '14 at 14:44
1

You could increment a count during the loop and compare it to the total amount of items.

var items = $j(".form-builder");
var count = items.length;

items.each(function(i){
  data_json+='{ "type":"'+$j(this).attr("type")+'"';
  if (i<count-1) {
     data_json+='},';
  }
  else {
     data_json += '}';
  }
});

This being said you should never build JSON like this. Instead refer to Matt Burland's answer as it is a much better way.

David Jones
  • 4,275
  • 6
  • 27
  • 51
0

Use counter to count iterations and compare to elements count

    var data_json = '';
 $(".form-builder").each(function(index, data){
      data_json+='{ "type":"'+$(this).attr("type")+'"';
      if (index + 1 == $(".form-builder").length) {
        alert('Last element is ' + (index + 1));
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' class='form-builder'/>
<input type='text' class='form-builder'/>
<input type='text' class='form-builder'/>
<input type='text' class='form-builder'/>
<input type='text' class='form-builder'/>
Justinas
  • 41,402
  • 5
  • 66
  • 96