...

View Full Version : Check for duplicates



ubh
09-12-2008, 04:02 PM
Hi, I have a little script here that when ran creates DIV boxes, it also sets a id for the div box by prompting the user to name the DIV box.

My question is can I preform some sort of duplicate checker to see if the user has already created a DIV box with the same (id), and if so then alert them they must pick a different name?



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addDiv()
{
var getId = prompt('Name New Div.','');
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
</script>
</head>

<body>
<button type="button" onclick="addDiv()">ADD NEW DIV</button>
<div id="wrap">
</div>
</body>
</html>

Mikebert4
09-12-2008, 04:38 PM
Try this:



function check4Dupes(name){
var divs = document.getElementsByTagName('div');
for (i=0; i<divs.length; i++){
if(divs[i].id == name){
return false;
}
}
return true;
}

function addDiv()
{
var getId = prompt('Name New Div.','');
if(getId){
if(check4Dupes(getId)){
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}else{
alert('div id already exists!');
}
}
}


That should do the trick :)


...or this (which is basically me having a play), to allow them to choose another name straight away:



function check4Dupes(name){
var divs = document.getElementsByTagName('div');
for (i=0; i<divs.length; i++){
if(divs[i].id == name){
return false;
}
}
return true;
}

function addDiv()
{
var getId = prompt('Name New Div.','');
if(getId){
if(check4Dupes(getId)){
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}else{
alert('Div already Exists! Pick a new name');
addDiv();
}
}
}

mrhoo
09-12-2008, 04:45 PM
function goodId(element,str){
var hoo;
if(!str){
str= element.tagName;
hoo= str+'_1';
}
else hoo=str;
var n=1;
while(document.getElementById(hoo))hoo=str+'_'+(++n);
element.setAttribute('id',hoo);
}

You don't want a name that was used anywhere in the document.
replace createDiv.setAttribute('id',getId) with goodId(createDiv,getId)

Philip M
09-12-2008, 04:51 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type = "text/javascript>

function addDiv() {
var getId = prompt('Name New Div. (Min 5 characters)',''); // reduce chances of duplication
if (getId == "" || getId == null || getId.length < 6) {
alert ("Invalid Input! Must be 5 characters minumum");
return false;
}

var divs = document.getElementsByTagName('div');
if (divs) {
for (var i = 0; i < divs.length; i++) {
if (divs[i].id == getId) {
alert ("That div name already exists - try again");
return false;
}
}
}

var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
</script>
</head>

<body>
<button type="button" onclick="addDiv()">ADD NEW DIV</button>
<div id="wrap">
</div>
</body>
</html>


Take my advice, I don't use it anyway.

Mikebert4
09-12-2008, 04:56 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addDiv()
{
var getId = prompt('Name New Div.','');

if(!getId){return false;}

var divs = document.getElementsByTagName('div');
if (divs) {
for (var i = 0; i < divs.length; i++) {
if (divs[i].id == getId) {
alert ("That div name already exists - try again");
return false;
}
}
}

var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
</script>
</head>

<body>
<button type="button" onclick="addDiv()">ADD NEW DIV</button>
<div id="wrap">
</div>
</body>
</html>


My turn again! - this'll handle the 'cancel' button on the prompt correctly as well.

(in case you feel swamped, all these solutions work :p)

vwphillips
09-12-2008, 04:59 PM
or

function addDiv()
{
var getId = prompt('Name New Div.','');
if (document.getElementById(getId)){
alert('Duplicate');
return false;
}
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}

Philip M
09-12-2008, 05:02 PM
=mrhoo;733058
You don't want a name that was used anywhere in the document.


Yes, good point.

One solution is to name other elements in an exotic way that is unlikely to be duplicated.

e.g. form name = "krv728formname"

Philip M
09-12-2008, 05:05 PM
function addDiv()
{
var getId = prompt('Name New Div.','');
if (document.getElementById(getId)){
alert('Duplicate');
return false;
}


That does not work - the id must be a literal string.

ubh
09-13-2008, 01:55 AM
WOOW thanks you all for your responses so much!!
I have everything working perfect now, thanks to you guys!!

You know I will have more questions down the line but for now thanks everyone!!

Arty Effem
09-13-2008, 02:45 AM
It may be critical to ensure that the ID is of an allowable format.

<script type='text/javascript'>
function addDiv()
{
do
{
var getId = prompt('Name New Div.', getId||""), result=0;

if( typeof getId==='string' )
{
if( !(getId = getId.replace(/^\s|\s$/g, '')).length || !/^[a-z][a-z0-9_\:\.]*$/i.test( getId ) )
alert('Incorrect format');
else
if( document.getElementById(getId) )
alert('ID already in use in the document');
else
result = 2;
}
else
result = 1;

}while( !result );

if(result==2)
{
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
}
</script>

Arty Effem
09-13-2008, 02:46 AM
That does not work - the id must be a literal string.I'm literally baffled by that.

Philip M
09-13-2008, 08:00 AM
I'm literally baffled by that.

Sorry, my brain hit a bad sector. :eek: Apologies to Vic.

vwphillips
09-13-2008, 11:41 AM
Apologies to Vic.
I had just retested it but no problem.

with more testing


var tt=true;
function addDiv()
{
var getId = prompt('Name New Div.','');
if (document.getElementById(getId)||window[getId]||!getId){
alert('Duplicate');
return false;
}
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}


as cancel produced a div, realy needs a reg ex to ensure a valid id name but thats Philip M province

Philip M
09-13-2008, 12:53 PM
as cancel produced a div, realy needs a reg ex to ensure a valid id name but thats Philip M province

Here is the final version incorporating Vic's comment:-


<script type = "text/javascript">

function addDiv() {
var getId = prompt('Name New Div.','');
if (getId) {
getId = getId.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
}
if ((getId == "") || (getId == null) || (getId.length < 6 )) {
alert ("Invalid Input! Must be 5 characters minumum");
return false;
}
if (/\W/.test(getId)) {
alert ("Invalid input! Name may contain letters and numbers only");
return false;
}
if (document.getElementById(getId)||window[getId]||!getId){
alert('Duplicate name - please try again!');
return false;
}
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
</script>

<button type="button" onclick="addDiv()">ADD NEW DIV</button>
<div id="wrap">
</div>

Mikebert4
09-14-2008, 03:24 PM
... did I miss somthing? why are we imposing a minimum string length?

anyway - based on the fact that -any- whitespace is bad news for id's, I'd propose the following slight modification to Philip M's code.




<script type = "text/javascript">
<!--

function addDiv() {
var getId = prompt('Name New Div.','');
if (getId) {
getId = getId.replace(/\s/g,""); // strip whitespace
}else{
return false; // handles cancel button
}
if ((getId == "") || (getId == null)) { //handles null/blank input
alert ("The Div must have a name!");
return false;
}
if (/\W/.test(getId)) { //handles invalid characters
alert ("Invalid input! Name may contain letters and numbers only");
return false;
}
if (document.getElementById(getId)||window[getId]){ //handles duplicates
alert('Duplicate name - please try again!');
return false;
}
var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
</script>

<button type="button" onclick="addDiv()">ADD NEW DIV</button>
<div id="wrap">
</div>
//-->


This little snippit is turning into a fine example of how a first solution - even a workable one - to any problem is rarely the best, rarely 'robust' and almost never elegant.

also - threads like this are good exercise :) keep it coming

Arty Effem
09-14-2008, 03:38 PM
based on the fact that -any- whitespace is bad news for id's, I'd propose the following slight modification to Philip M's code.

I did that already.


if (/\W/.test(getId)) { //handles invalid characters
alert ("Invalid input! Name may contain letters and numbers only");
return false;
As I understand it colons underscores and periods are allowed and you haven't coded to reject a non-alphabetic prefix.

Philip M
09-14-2008, 08:06 PM
Agreed best to strip all spaces. But I did in fact cover the white space issue:-

if (/\W/.test(getId)) {
alert ("Invalid input! Name may contain letters and numbers only"); // no spaces or other special characters apart from _
return false;
}

Colons and periods may be allowed in a technical sense but common sense suggests that they be not permitted here. KISS.

if ((getId == "") || (getId == null) || (getId.length < 6 )) {
alert ("Invalid Input! Must be 5 characters minumum");
return false;
}

deals with the cancel button.

Obviously the OP can choose the minimum length of name allowed, but it makes sense to require a "meaningful" name even if the five chars is arbitrary.
But that can be dispensed with if desired. But the shorter the name the more likely the user is to duplicate it.



I did have a reason for not stripping all spaces (rather than just leading and trailing spaces) at the outset. If a user enters abc xyz as the name, your script will strip the space and create a div named abcxyz without further warning. Mine will reject the name and alert. I assume this matters as presumably the user needs to know/remember the name for later use or reference - otherwise the div names could simply be created automatically as div1, div2, div3 etc.

However, the same objection applies to my script if the user enters a name of 5 chars or more plus leading or trailing spaces. space space abcxyz. And as a Javascript identifier may not start with a digit it is necessary to disallow that also.

I am therefore suggesting the following adjustment to the script to reject all invalid characters at the outset:-

function addDiv() {
var getId = prompt('Name New Div.','');
if (getId) {
if (/\W/.test(getId)) {
alert ("Invalid input! Name may contain letters and numbers only"); // no need to mention underscore!
return false;
}
if (/^\d/.test(getId)) {
alert ("Invalid input! Name may not start with a digit");
return false;
}
}
if ((getId == null) || (getId.length < 6 )) {
alert ("Invalid Input! Must be 5 alphanumeric characters minumum");
return false;
}


Naturally the 'rules' for div names will be specified/displayed.

Mikebert4
09-15-2008, 09:55 AM
I'm caught-up with your thinking now Philip :) thanks

Another benefit of specifying a minimum-length for added DIVs is that you can remove any posibility of the users id's matching ones in your code by keeping the length of all your id's below this figure.

Based on your edit - wouldn't it be prudent to check for leading spaces at the outset and alerting the user that these have been trimmed - I don't think you would fail the name at that point, but something along the lines of:





if(/^\s+/.test(getId){
alert('Leading spaces not allowed - trimming');
getId = getId.replace(/^\s+/,"");
}



so the finished article would look like:




<script type = "text/javascript">
<!--
function addDiv() {
var getId = prompt('Name New Div.','');

if (getId) {
if(/^\s+/.test(getId){ //handles and trims leading spaces
alert('Leading spaces not allowed - trimming');
getId = getId.replace(/^\s+/,"");
}
if (/\W/.test(getId)) { //handles non-alphanumeric
alert ("Invalid input! Name may contain letters and numbers only"); // no need to mention underscore!
return false;
}
if (/^\d/.test(getId)) { //handles non-alphabetical start
alert ("Invalid input! Name may not start with a digit");
return false;
}
}
if ((getId == null) || (getId.length < 6 )) { //handles string-length issues
alert ("Invalid Input! Must be 5 alphanumeric characters minumum");
return false;
}
if (document.getElementById(getId)||window[getId]){ //handles duplicates
alert('Duplicate name - please try again!');
return false;
}

var getWrap = document.getElementById("wrap");
var createDiv = document.createElement("div");
createDiv.setAttribute('id',getId);
createDiv.style.width="128px";
createDiv.style.height="128px";
createDiv.style.float="left";
createDiv.style.marginTop="5px";
createDiv.style.backgroundColor="#000";
getWrap.appendChild(createDiv);
}
//-->
</script>

<button type="button" onclick="addDiv()">ADD NEW DIV</button>
<div id="wrap">
</div>

Philip M
09-15-2008, 10:26 AM
Based on your edit - wouldn't it be prudent to check for leading spaces at the outset and alerting the user that these have been trimmed - I don't think you would fail the name at that point, but something along the lines of:



OK, but the same logic surely applies to trailing or intermediate spaces as well.


if(/\s+/g.test(getId){
alert ('Spaces are not allowed - trimming');
getId = getId.replace(/\s+/g,""); // strip all spaces
}

Mikebert4
09-15-2008, 11:27 AM
OK, but the same logic surely applies to trailing or intermediate spaces as well.


if(/\s+/g.test(getId){
alert ('Spaces are not allowed - trimming');
getId = getId.replace(/\s+/g,""); // strip all spaces
}

I agree for trailing spaces, though any intermediate spaces are covered nicely by your /\W/ regexp and I think we decided that it was better to fail the ID on intermediate spaces, rather than trim them out.

so - we end up with leading and trailing spaces getting trimmed, thus:



if(/^\s+|\s+$/g.test(getId){
alert ('Leading/Trailing spaces not allowed. Trimming.');
getId = getId.replace(/^\s+|\s+$/g,""); // strip all spaces
}



Which actually brings us almost completly back to your complete code from your post on 09-13-2008 at 12:53 PM.

*takes off hat*



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum