Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery, how can I check that a collection of input elements have unique values?

Tags:

jquery

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?

like image 917
loviji Avatar asked Mar 10 '10 17:03

loviji


2 Answers

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>
like image 141
St.Woland Avatar answered Nov 12 '22 06:11

St.Woland


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.

like image 26
Nick Craver Avatar answered Nov 12 '22 06:11

Nick Craver