How to compare 2 elements with same getElementById(x)?

V

vadymus

Hello,
I need to compare 2 id names but not their values. For example:

document.getElementById(i) == document.getElementById(j)

these elements above seem to give error or do not work.
My original statement is this (and note, when I add line above to it,
that does not work):

function uniqueValues(){
var myForm = document.add2db;
var iMax = myForm.imax.value;
//var IsSimilar, IsSame;
for (i=0;i<iMax;i++)
{

var fieldValue=document.getElementById(i).value;
alert("id is "+document.getElementById(i));
for(j=0;j<iMax;j++)
{
var fieldValue2=document.getElementById(j).value;
if ((fieldValue == fieldValue2) && (document.getElementById(i) !=
document.getElementById(j))) { //FIX HERE
alert("I am sorry, but these values are identical:
"+document.getElementById(j).value);
document.getElementById(j).focus();
return false;
}
}
}
//return true;
}
 
B

bwucke

I need to compare 2 id names but not their values. For example:
document.getElementById(i) == document.getElementById(j)

Well, there's this method, .isEqualNode() but since IDs are supposed to
be unique, in your case i==j should perfectly suffice.
 
L

Lee

(e-mail address removed) said:
Hello,
I need to compare 2 id names but not their values. For example:

document.getElementById(i) == document.getElementById(j)

these elements above seem to give error or do not work.

Maybe I'm missing something, but why don't you just compare
the two id's? "if (i==j)". You should never have two elements
with the same id.
 
V

vadymus

Thank you so much...
I did finf .name but it did not work for me. Identical id's are not
recognized (maybe I do smth wrong?):

function uniqueValues(){
var myForm = document.add2db;
var iMax = myForm.imax.value;
for (i=0;i<iMax;i++)
{

var fieldValue=document.getElementById(i).value;
//alert("id is "+document.getElementById(i).name);
for(j=0;j<iMax;j++)
{
var fieldValue2=document.getElementById(j).value;
if ((fieldValue == fieldValue2) && (document.getElementById(i).name
!= document.getElementById(j).name)) { //FIX HERE
alert("I am sorry, but these values are identical:
"+document.getElementById(j).value);
document.getElementById(j).focus();
return false;
}
}
}
//return true;
}



I am going to try .isEqualNode() now
 
V

vadymus

Lee, you are absolutely right i and j can be compared. I cannot believe
it is more simple that I thought. However, my script does not catch
identical values here still.

I try to submit form with unique field values as below.
- imax is the number of fields.
- all unique field values are from textarea called texarea0, textarea1,
.......texareaN (all together is imax)
- these texarea fields have unique html IDs: 0, 1, 2, 3.....N

Code below does not catch nonubique values eventhough there are no
errors when run

function uniqueValues(){
var myForm = document.add2db;
var iMax = myForm.imax.value;
for (i=0;i<iMax;i++)
{

var fieldValue=document.getElementById(i).value;
//alert("id is "+document.getElementById(i).name);
for(j=0;j<iMax;j++)
{
var fieldValue2=document.getElementById(j).value;
if ((fieldValue == fieldValue2) && (i!=j)) { //FIX
HEREdocument.getElementById(i).name != document.getElementById(j).name
alert("I am sorry, but these values are identical:
"+document.getElementById(j).value);
document.getElementById(j).focus();
return false;
}
}
}
//return true;
}
 
B

bwucke

(e-mail address removed) napisal(a):
Lee, you are absolutely right i and j can be compared. I cannot believe
it is more simple that I thought. However, my script does not catch
identical values here still.

I try to submit form with unique field values as below.
- imax is the number of fields.
- all unique field values are from textarea called texarea0, textarea1,
.......texareaN (all together is imax)
- these texarea fields have unique html IDs: 0, 1, 2, 3.....N

Code below does not catch nonubique values eventhough there are no
errors when run

function uniqueValues(){
var myForm = document.add2db;
var iMax = myForm.imax.value;
for (i=0;i<iMax;i++)
{

var fieldValue=document.getElementById(i).value;
//alert("id is "+document.getElementById(i).name);
for(j=0;j<iMax;j++)
{
var fieldValue2=document.getElementById(j).value;
if ((fieldValue == fieldValue2) && (i!=j)) { //FIX
HEREdocument.getElementById(i).name != document.getElementById(j).name
alert("I am sorry, but these values are identical:
"+document.getElementById(j).value);
document.getElementById(j).focus();
return false;
}
}
}
//return true;
}

Not sure what's the problem now, but I see you're doing quite a few too
many checks. That is, say, i=3, j=5, then j=3, i=5 will check the same.

for (i=0; i < iMax-1 ; i++)...
{
....
for(j=i+1;j<iMax;j++)
{
....
if (fieldValue == fieldValue2)
{

then i will never be equal to j and still all pairs get checked.

Maybe send a piece of HTML, possible that you're mishandling IDs there
somehow.
 
R

RobG

Lee, you are absolutely right i and j can be compared. I cannot believe
it is more simple that I thought. However, my script does not catch
identical values here still.

I try to submit form with unique field values as below.
- imax is the number of fields.
- all unique field values are from textarea called texarea0, textarea1,
.......texareaN (all together is imax)
- these texarea fields have unique html IDs: 0, 1, 2, 3.....N

This indicates that your HTML is invalid. IDs can include numbers,
but can't start with them.

Code below does not catch nonubique values eventhough there are no
errors when run

The following loops through all the elements of the form and barfs
when the first duplicate value is reached:

function uniqueValues()
{
var val, vals = {};
var el, els = document.forms['add2db'].elements;

for (var i=0, len=els.length; i<len; ++i){
el = els;
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;
}
vals[val] = val;
}
}


[...]
 
T

Thomas 'PointedEars' Lahn

val = el.value
if (vals[val]){ }
vals[val] = val;

except if the user enters two zeros.

vals[val] = true;

What are you talking about? `vals' is a reference to an Object object.
Property names as well as form controls' values are _string_ values:

var vals = {"0": "0"}, val = "00";
if (vals[val])
{
// will never be executed
}

One problem that remains, however, is that Object objects inherit
properties from Object, so that test is not reliable; for retaining
and those inherited property values and avoiding false positives, it
is necessary to map form controls' values that correspond to those
properties' names to unused property names; one may instead also use
Object.prototype.hasOwnProperty() where supported.

Please quote the minimum of what you are replying to and provide
attribution of quoted material:

<URL:http://jibbering.com/faq/faq_notes/pots1.html#ps1Post>
<URL:http://www.safalra.com/special/googlegroupsreply/>


PointedEars
 
V

vadymus

Hello,
The code offered by RobG returns "Already have 0" alert and exists. It
does not find all similar values. Please, suggest something, if
possible...

function uniqueValues()
{
var val, vals = {};
var el, els = document.forms['add2db'].elements;

for (var i=0, len=els.length; i<len; ++i){
el = els;
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;
}
vals[val] = val;
}
}
 
V

vadymus

Well, actually I was right, my version works except that it takes 5
minutes to check 192 fields. Any suggestions to improve code below?

function uniqueValues(){
var myForm = document.add2db;
var iMax = myForm.imax.value;
for (i=0;i<iMax;i++)
{

var fieldValue=document.getElementById(i).value;
//alert("id is "+document.getElementById(i).name);
for(j=0;j<iMax;j++)
{
var fieldValue2=document.getElementById(j).value;
if ((i!=j) && (fieldValue == fieldValue2)) { //FIX HERE
alert("I am sorry, but these values are identical:
"+document.getElementById(j).value);
document.getElementById(j).focus();
return false;
}
}
}
return true;
}
 
J

Jonas Raoni

(e-mail address removed) escreveu:
Well, actually I was right, my version works except that it takes 5
minutes to check 192 fields. Any suggestions to improve code below?

As another guy said, it isn't right to have a field's id starting with
a number, so in the example bellow, I changed to t0, t1, t2...

<form id="add2db">
<input type="text" id="t0" value="0" />
<input type="text" id="t1" value="1" />
<input type="text" id="t2" value="2" />
<input type="text" id="t3" value="3" />
<input type="hidden" id="imax" value="4" />
<input type="button" onclick="uniqueValues();" value="Test" />
</form>

<script type="text/javascript">
function uniqueValues(){
for(var f = document.forms.add2db, i = f.imax.value, j, o; i; )
for(j = --i; j;)
if(f["t" + i].value == (o = f["t" + --j]).value)
return o.focus(), o.select(), alert("I am sorry, but the values are
identical."), false;
return true;
}
</script>

I hope it will help...
 
T

Thomas 'PointedEars' Lahn

The code offered by RobG returns "Already have 0" alert and exists.
It does not find all similar values. Please, suggest something, if
possible...

Gladly. Would you please quote what you reply to and provide
attribution of quoted material?

<URL:http://jibbering.com/faq/faq_notes/pots1.html#ps1Post>
function uniqueValues()
{
var val, vals = {};
var el, els = document.forms['add2db'].elements;

for (var i=0, len=els.length; i<len; ++i){
el = els;
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;


Remove that line to prevent the function from exiting. Remove other lines
in that block if you do not need the respective feature.

If the code is to find all equal or similar values, I suggest you use an
Array for property value. Say you want to have an array of references of
all equal values in the form, you could do

var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els, val = el.value;
if (vals[val])
{
vals[val].push(el);
}
else
{
// Creates a new Array object with the `el' reference as only
// element and assigns a reference to that Array object to a
// property of the Object object referred to by `vals';
// use `new Array(...)' where Array literals are not supported.
vals[val] = [el];
}
}

vals["0"] would then be a reference to an Array object encapsulating a list
of references to all form elements that have value "0". If instead you
want to find all similar values, you would need to define what you consider
to be similar first; then an appropriate hash function can provide for
mapping the similar value to a property.

Note that the inheritance caveat I mentioned before in
would still apply.


PointedEars
 
R

RobG

Jonas Raoni wrote:

[...]
<script type="text/javascript">
function uniqueValues(){
for(var f = document.forms.add2db, i = f.imax.value, j, o; i; )
for(j = --i; j;)
if(f["t" + i].value == (o = f["t" + --j]).value)
return o.focus(), o.select(), alert("I am sorry, but the values are
identical."), false;
return true;
}
</script>

I hope it will help...

But it's very inefficient, it will require n^2 checks to be performed
(where n is the number of inputs to check).

My first post simply stopped at the first match as designed. Thomas'
final version likely suits the OP better.
 
R

RobG

Thomas 'PointedEars' Lahn wrote:

[...]
var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els, val = el.value;
if (vals[val])


If there is a concern that vals[val] may be evaluated incorrectly, then:

if (val in vals)


will be better - it works with empty values too. I can't think why I
didn't go that way in the first place.


[...]
 
B

bwucke

RobG said:
Thomas 'PointedEars' Lahn wrote:

If there is a concern that vals[val] may be evaluated incorrectly, then:

if (val in vals)

and if user enters 'constructor' in any field?

var vals=new Object;
alert('constructor' in vals);

Tricky :)
 
J

Jonas Raoni

RobG escreveu:
But it's very inefficient, it will require n^2 checks to be performed
(where n is the number of inputs to check).

Hmm, it's not "n ^ 2", but n ^ 2 / 2 + n / 2 since it works this way:

abcd
abc
ab
a

Your version do n ^ 2 loops, but due to the fact that the inner loop
("x in y") is done internally, i have no doubt that it will work faster
than mine one =]

Anyway, it wasn't my intention to make a better code, I just wanted to
help that guy "Any suggestions to improve code below?"
 
R

RobG

RobG said:
Thomas 'PointedEars' Lahn wrote:

If there is a concern that vals[val] may be evaluated incorrectly, then:

if (val in vals)


and if user enters 'constructor' in any field?

var vals=new Object;
alert('constructor' in vals);

Good point.

But fixable:

if (val in vals && 'string' == typeof vals[val]) {
// ...
}
 
R

Richard Cornford

RobG said:
Thomas 'PointedEars' Lahn wrote:

[...]
var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els, val = el.value;
if (vals[val])


If there is a concern that vals[val] may be evaluated
incorrectly, then:

if (val in vals)


That wouldn't help as the in operator calls the object's [[HasProperty]]
method, and if the object itself has no property with the given name the
[[HasProperty]] method calls the [[HasProperty]] method of the object's
prototype (and so on up the prototype chain). So a value with a name
such as, for example, "toString" will collide with a function reference.

Given that the next line of code calls a - push - method on whatever is
referred to by - vals[val] -, a safer test might be:-

if((vals[val])&(vals[val].push)){ ...

- as then the Array nature of the objects assigned as properties of the
object would be verified (assuming no prototype augmentation to provide
an inherited property of Object that was an Array, and no introduction
of - push - methods on other object types).

The problem here is the oft-discussed reason that it is unwise to speak
of javascript objects as 'HashTables' or 'associative arrays'; a
javascript object is never 'empty'. If the property names used in such a
context are to be truly arbitrary (as opposed to a known set where
collisions with object prototype properties can be know not to be an
issue) then the only real solution is a programmer-defined storage
object that deals with naming issues internally.
will be better -

Generally the binary - in - operator is of little value or use in
javascript programming, testing the nature of the value returned with a
property accessor in a way that reliably puts - undefined - on the
'rejected' side of the test will invariably be more discriminating and
reliable. (A big clue that this is the case may be found in the fact
that VK is the _only_ individual to have proposed the use of the - in -
operator in a general programming context; anything VK chooses may be
regarded as highly suspect for no other reason).
it works with empty values too.
<snip>

I don't really understand what you mean here as objects may have
properties named with any sequence of charters, including an empty
string. I don't think I would encourage people to give object's
properties named with the empty string because that would be an
invitation to encounter implementation bugs, but properties named with
empty sequences of characters are completely legal by ECMA 262.

Richard.
 
T

Thomas 'PointedEars' Lahn

Richard said:
The problem here is the oft-discussed reason that it is unwise to speak
of javascript objects as 'HashTables' or 'associative arrays'; a
javascript object is never 'empty'. If the property names used in such a
context are to be truly arbitrary (as opposed to a known set where
collisions with object prototype properties can be know not to be an
issue) then the only real solution is a programmer-defined storage
object that deals with naming issues internally.

Maybe I was misunderstood; to ensure I am not: that "programmer-defined
object that deals with naming issues internally" is one way to implement
what I called "an appropriate hash function" that "can provide for mapping
the similar value to a property." I was not, by all means, referring to
objects as hash tables or associative arrays.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top