How to use jquery, how can I verify that a set of input elements has unique values?

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

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

+7
jquery
source share
2 answers

Nick's solution has O (n 2 ) complexity. Here is an optimized example.

The isUnique function determines the desired 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> 
+6
source share

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

 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 the vals before the second pass if you reuse it.

+4
source share

All Articles