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?
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>
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With