notify
notify

Reputation: 59

.each() after a .clone() for validation function

I am using jquery validation but there is no option to check for error type's.

Because of that I am trying to build my own validation function but I am struggling to get the each function to work after I cloned a row.

It always returns with the same data of the first selection box.

I have made a jsfidlle for more detail on the problem : https://jsfiddle.net/notify/b22dctdo/

What I want to achieve is that if there is a duplicate value on the select-boxes that I generate a div with an error message.

Maybe I am looking in the wrong direction but hope someone can point me in the correct direction. I want to use the function inputsHaveDuplicateValues what i have found and have made a test function that returns the data-index number for better view.

function inputsHaveDuplicateValues() {
  var hasDuplicates = false;
  $('li.selected').each(function() {
    var $inputsWithSameValue = $(this).data("original-index");
    hasDuplicates = $inputsWithSameValue.length > 1;
    //This will break out of the each loop if duplicates have been found.
    return hasDuplicates;
  });
  return hasDuplicates;
};

Many thanks in Advance for looking into this.

Upvotes: 0

Views: 72

Answers (1)

Blazemonger
Blazemonger

Reputation: 92983

$(this).data("original-index") returns a number, not a jQuery object. I think you want to filter the set of dropdowns.

Also, you break out of .each() by returning false, not true.

function test() {
  $("ul.inner").each(function(index, element) {
    alert("Test Function -> " + $("li.selected",this).data("original-index"));
  });
};

function inputsHaveDuplicateValues() {
  var hasDuplicates = false;
  $('li.selected').each(function() {
    var originalIndex = $(this).data("original-index"),
      $inputsWithSameValue = $("ul.inner").filter(function() {
        return $('li.selected',this).data('original-index') == originalIndex;
      });
    hasDuplicates = $inputsWithSameValue.length > 1;
    //This will break out of the each loop if duplicates have been found.
    return !hasDuplicates;
  });
  return hasDuplicates;
};

// on button check
$("#check").click(function(event) {
  test()
  alert("Duplicate function -> " + inputsHaveDuplicateValues());
});

https://jsfiddle.net/op93cbyz/

Upvotes: 1

Related Questions