-4

I have the following function called twice:

function (data) {
   $.each(data.items, function(i,item) {    
                  var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" value="valuable" id="thing_'+i+'"/><label for="thing_'+i+'"><img class="img-responsive" src="' + item.link + '"></label></div></div>');`enter code here`

It generates checkboxes and I am generating the identifier name for and id with the i, giving me:

thing_1
thing_2
thing_3

The problem is that when I run the function the second time, the i starts again, resulting in duplicated ids and name and for

rob.m
  • 9,843
  • 19
  • 73
  • 162

1 Answers1

1

Use an IIFE:

var uniqueId = (function() {
  var counter = 0;

  return function(prefix) {
    counter++;
    return prefix ? prefix + '' + counter : counter;
  }
})();

console.log(uniqueId()); // 1
console.log(uniqueId()); // 2
console.log(uniqueId('thing_')); // thing_3
console.log(uniqueId('thing_')); // thing_4

You would integrate it in your code like this:

function (data) {
  $.each(data.items, function(i, item) {
    var uniq = uniqueId('thing_');
    var $items = $('<div class="col-sm-4 grid-item">'.concat(
      '<div class="thumbnail">',
      '<input type="checkbox" name="', uniq, '" value="valuable" id="', uniq, '" />',
      '<label for="', uniq, '">',
        '<img class="img-responsive" src="' + item.link + '">',
      '</label>',
    '</div>',
  '</div>'));

I broke your huge HTML mess on multiply lines using String.prototype.concat

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123