By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,623 Members | 1,904 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,623 IT Pros & Developers. It's quick & easy.

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

P: n/a
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;
}

Dec 22 '05 #1
Share this Question
Share on Google+
21 Replies


P: n/a
> 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.

Dec 22 '05 #2

P: n/a
<va*****@gmail.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
Hello,
I need to compare 2 id names but not their values. For example:

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


Try:

document.getElementById(i).name == document.getElementById(j).name
Dec 22 '05 #3

P: n/a
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

Dec 22 '05 #4

P: n/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;
}

Dec 22 '05 #5

P: n/a

va*****@gmail.com 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.

Dec 23 '05 #6

P: n/a
va*****@gmail.com wrote:
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[i];
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;
}
vals[val] = val;
}
}
[...]
--
Rob
Dec 23 '05 #7

P: n/a
> val = el.value
if (vals[val]){ }
vals[val] = val;


except if the user enters two zeros.

vals[val] = true;

Dec 23 '05 #8

P: n/a
bw****@gmail.com wrote:
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
Dec 23 '05 #9

P: n/a
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[i];
val = el.value
if (vals[val]){
alert('Already have ' + val);
if (el.focus) el.focus();
return;
}
vals[val] = val;
}
}

Dec 23 '05 #10

P: n/a
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;
}

Dec 23 '05 #11

P: n/a
va*****@gmail.com 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...

--
Jonas Raoni Soares Silva
http://www.jsfromhell.com

Dec 23 '05 #12

P: n/a
va*****@gmail.com wrote:
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>
<URL:http://www.safalra.com/special/googlegroupsreply/>
function uniqueValues()
{
var val, vals = {};
var el, els = document.forms['add2db'].elements;

for (var i=0, len=els.length; i<len; ++i){
el = els[i];
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[i], 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
news:13****************@PointedEars.de would still apply.
PointedEars
Dec 23 '05 #13

P: n/a
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.
--
Rob
Dec 25 '05 #14

P: n/a
Thomas 'PointedEars' Lahn wrote:

[...]
var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els[i], 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.
[...]
--
Rob
Dec 25 '05 #15

P: n/a

RobG wrote:
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 :)

Dec 25 '05 #16

P: n/a
RobG escreveu:
Jonas Raoni wrote:
<script type="text/javascript">
function uniqueValues(){
:
}
</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).


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?"
--
Jonas Raoni Soares Silva
http://www.jsfromhell.com

Dec 25 '05 #17

P: n/a
bw****@gmail.com wrote:
RobG wrote:
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.

Tricky :)


But fixable:

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

--
Rob
Dec 27 '05 #18

P: n/a
RobG wrote:
Thomas 'PointedEars' Lahn wrote:

[...]
var vals = {};
for (var i = 0, len = els.length; i < len; ++i)
{
var el = els[i], 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.
Dec 28 '05 #19

P: n/a
Richard Cornford wrote:
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
Dec 28 '05 #20

P: n/a
Richard Cornford wrote:
[...]
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 test would fail with JavaScript < 1.2 (NN < 4), JScript < 5.5 (IE < 5.5)
and ECMAScript < 3. A more reliable test would be

if (vals[val] && vals[val].constructor == Array)
{
// ...
}

since that would only fail with JavaScript < 1.1 (NN < 3) and JScript < 2.0
(IE < 4.0).

Of course, for the above versions without native Array.prototype.push()
support, one could augment the prototype before (with all side-effects of
user-defined properties):

if (typeof Array.prototype.push == "undefined")
{
Array.prototype.push = function Array_push()
{
for (var i = 0, len = arguments.length; i < len; i++)
{
this[this.length] = arguments[i];
}
}
}
PointedEars
Dec 28 '05 #21

P: n/a
Thank you all. I will try your suggestions when I get to my testing
area.
Happy holidays!!!

Dec 28 '05 #22

This discussion thread is closed

Replies have been disabled for this discussion.