Im trying to add some serial numbers from a number n of text boxes to an array at the same time I want to make sure that no duplicates are being entered. Here is my code:
Code:
function GetSerials() {
var count_1 = 0;
var serialArray = new Array;
var id = "1serial_"+count_1;
var element = document.getElementById(id).value;
serialArray.length = 1;
try
{
duplicate:
while (element != null)
{
var id = "1serial_"+count_1;
var element = document.getElementById(id).value;
for(x=0;x<serialArray.length;x++)
{
if(element == serialArray[x])
{
alert("You can not use duplicate serial numbers");
serialArray.length = 0;
break duplicate;
}
else
{
serialArray.push(element);
}
}
count_1++;
}
}catch(err)
{
alert(serialArray);
}
}
<html>
<head>
</head>
<body>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="button" onclick="checkDupes()" value="check"/>
<script>
var tbs=document.getElementsByTagName("input");
var serials=[];
function checkDupes(){
serials.length=0;
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type=="text"){
if (serials.indexOf(tbs[i].value)==-1){
serials.push(tbs[i].value);
} else {
alert("You can not use duplicate serial numbers - serial number "+tbs[i].value+ " repeated");
return;
}
}
}
alert(serials.toString())
}
</script>
</body>
</html>
It might be easier to create an object of serial numbers, and then put them into the array, depending on how many you have.
Code:
var dupes = {};
var serialNumbers = [];
for (var i = 0; i < how_ever_many; i++) {
var e = /* however you get them */;
if (dupes[e]) {
// Duplicate
}
else {
dupes[e] = true;
// not duplicate
}
}
Obviously you can't just rely on JavaScript to do this if you're uploading it to a server or something, this is just an initial check.
Great wit and madness are near allied, and fine a line their bounds divide.
Im going to try both method and yes Im using AJAX/php to put things on the server the problem Im having is that this serial numbers may be accompannied by a small comment and on top of that this are pipes used in the oil business, therefore they have also a size. My boss kinda threw me under the bus with this one.
yea so far the only thing that I cant seem to figure out is how to tie a comment to a particular serial number to then sent it to be saved in the database
var serials = {};
serials[curentSerial] = curentSerial;
//or bettermore:
Code:
serials[curentSerial] = index;
this way dpes will be overwritten automatically. And you can access them wit the in operator +check the index value so you would also know which field was dupped.
If you absolutely need to tie the variable together with a comment then first encode the string somehow, like by using the escape() function then add it to the serial using a separator character such as a : or | then when you need to search for duplicate serials use a RegExp object, i'm pretty sure it can be used with indexOf.
Bookmarks