view raw
Raffy T Lawrence Raffy T Lawrence - 9 months ago 28
HTML Question

Javascript: How to check if each input value is duplicated to another input value

So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.

This would look like

The first criteria_name is default and the others are appendend.

<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">

I am trying to check each one of those if there is no duplicated else proceed.

var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;

for(var ab = 2; ab<=acappended; ab++){
var crit_arr;

if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;

input_check = $('input.criteria_each_name'+ab);
crit_arr = $.trim($(this).val());
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;


Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:


    $('.ter').click(function(e) {
        var stored  =   [];
        var inputs  =   $('.criteria_name');
            var getVal  =   $(v).val();
            if(stored.indexOf(getVal) != -1)
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />