Created
July 18, 2011 04:06
-
-
Save samwilson/1088523 to your computer and use it in GitHub Desktop.
Preventing duplicate rows in a tabular HTML form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$().ready(function() { | |
// Save the current value of a select when it gains focus, to | |
// be used in case the value is changed. | |
$("table select").live('focus', function(){ | |
$(this).data('oldVal',$(this).val()); | |
}); | |
//After changing a value in any row, | |
$("table select").live('change',function() { | |
//get a list of the values in that row | |
var values = []; | |
$(this).closest("tr").find("input,select,textarea").each(function() { | |
values.push($(this).val()); | |
}); | |
//and then go through all rows | |
var matchCount = 0; | |
$(this).closest("tbody").find("tr").each(function(){ | |
//and see if those values are there. | |
var match = true; | |
for (var i = 0; i < values.length; i++) { | |
var currVal = $(this).find("td:nth-child("+(i+1)+")").find("input,select,textarea").val(); | |
match = match && (values[i]==currVal); | |
} | |
if (match) matchCount++; | |
}); | |
// If we find more than one instance of them, | |
if (matchCount > 1) { | |
//tell the user | |
$(this).effect("highlight", {color:"#ff0000"}, 800); | |
//and return the changed value to what it was before. | |
$(this).val($(this).data('oldVal')); | |
} | |
}); | |
}); | |
// For more information, please see http://samwilson.id.au/2011/07/12/tabular-forms/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment