tags:

views:

152

answers:

2

I have a table. Some rows are dynamically added by jquery.

The first <td> of each row has an <input type="text" /> element. Using jQuery, is it possible to check that all these input elements have unique values?

+3  A: 

You can use an array for this and the jQuery .inArray function like this:

var vals = new Array();
$("td:first-child input").each(function() {
  if($.inArray($(this).val(), vals) == -1) { //Not found
     vals.push($(this).val());
  } else {
    alert("Duplicate found: " + $(this).val());
  }      
});

Be sure to clear vals before a second pass if you're reusing it.

Nick Craver
+5  A: 

Nick's solution has O(n2) complexity. Here's an optimized example.

Function isUnique determines the required result.

<script src="jquery.js" />
<script>
function isUnique( tableSelector ) {
    // Collect all values in an array
    var values = [] ;
    $( tableSelector + ' td:first-child input[type="text"]' ).each( function(idx,val){ values.push($(val).val()); } );

    // Sort it
    values.sort() ;

    // Check whether there are two equal values next to each other
    for( var k = 1; k < values.length; ++k ) {
        if( values[k] == values[k-1] ) return false ;
    }
    return true ;
}

// Test it
$(document).ready(function(){
    alert( isUnique( ".myTable" ) ) ;
});
</script>

<table class="myTable">
    <tr><td><input type="text" value="1" /></td></tr>
    <tr><td><input type="text" value="2" /></td></tr>
</table>
St.Woland
This loops through the array 3 times plus a sort...the performance difference would take a hundred thousand loops to make 1ms, all your time is spent in the selector in this case. For things like this I'll take more straight-forward code than .000001ms improvements in execution time any day of the week :)
Nick Craver
I'd consider having two options, one for every possible scenario (of course, your solution works much better for a long array with equal values in the beginning; mine will be faster, if they are in the end). Besides, there are idealists, who live to produce a better-looking code ;)
St.Woland
Agreed, depends where the duplicates are...I suppose I'm not in the habit of making pages large enough that the performance would have more than a .0000001ms difference, so I opt for the cleanest code approach...or rather what seems the cleanest to me.
Nick Craver
Thanks, for your answers. But I find it difficult to choose the best answer.
loviji
@loviji - This one, St deserves rep for the analysis, and I'm capped for the day :)
Nick Craver
Would it work and be faster to do it this way ? (sorry for the formatting) :function isUnique( tableSelector ) { var o=true,v,values = {}; $( tableSelector + ' td:first-child input[type="text"]' ) .each( function(idx,val){ v=$(val).val(); if ( values[v]) { o=false;return false }; values[v]= true; }); return o;}
David V.